【发布时间】: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