【问题标题】:Python abstractclass InheritancePython抽象类继承
【发布时间】:2021-10-24 11:57:09
【问题描述】:

我有两个类结构如下

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 实例化抽象类 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 D(C):
    @C.x.setter
    def x(self, val):
        ...

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

【问题讨论】:

    标签: python inheritance metaclass


    【解决方案1】:

    当您在 setter 上方写入 @C.x.setter 时,您将 x 设置为 C.x 的版本,并将 setter 替换为新的 setter 函数。 只有 setter - 你之前写的 getter 会被丢弃。你还在使用C.x 的抽象getter。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多