Python 抽象类继承

Python abstractclass Inheritance

我有两个 class 结构如下

from abc import ABCMeta, abstractmethod


class C(metaclass=ABCMeta):
    """"""

    def __init__(self, x, y):
        self._x = x
        self._y = y

    @property
    @abstractmethod
    def x(self):
        """Get the _x"""

    @x.setter
    @abstractmethod
    def x(self, value):
        """Set the x"""

    @property
    def y(self):
        """Get the _y"""

    @y.setter
    def y(self, value):
        """Set the _y"""


class D(C):
    """"""

    def __init__(self, x, y):
        self._x = x
        self._y = y

    @property
    def x(self):
        return self._x

    @C.x.setter
    def x(self, value):
        self._x = value

    @property
    def y(self):
        return self._y

    @C.y.setter
    def y(self, value):
        self._y = value

当我初始化 D 的一个实例时,它抛出一个错误: TypeError: 无法使用抽象方法 x

实例化抽象 class D

当我将 D 中的 setters 装饰器重写为

@x.setter
def x(self, value):
    self._x = value

有效。但是在 python abc 文档 https://docs.python.org/3/library/abc.html 中它指出: 在被贬低的@abc.abstractproperty 如果只有一些组件是抽象的,那么只有那些组件需要更新以在子class:

中创建一个具体的属性
class D(C):
    @C.x.setter
    def x(self, val):
        ...

不知道为什么这样写会出错。请帮助我理解这里的逻辑。谢谢。

当您在 setter 上方写 @C.x.setter 时,您将 x 设置为 C.x 的版本,其中 setter 替换为您的新版本setter 函数。 只有 setter - 你之前写的getter被丢弃了。您仍在使用 C.x 的摘要 getter。

文档中的示例使用 @C.x.setter 因为他们 想要 它提供的行为。在文档示例中,C.x 有一个具体的 getter,他们只是想替换 setter。你的代码不是这种情况。