考虑下面的示例代码:抽象属性不强制
from abc import ABC, abstractmethod, abstractproperty
class Base(ABC):
@abstractmethod
def foo(self) -> str:
print("abstract")
@property
@abstractmethod
def __name__(self) -> str:
return "abstract"
@abstractmethod
def __str__(self) -> str:
return "abstract"
@property
@abstractmethod
def __add__(self, other) -> str:
return "abstract"
class Sub(Base):
def foo(self):
print("concrete")
def __str__(self):
return "concrete"
def __add__(self, other) -> str:
return "concrete"
sub = Sub()
sub.foo()
sub.__name__
print(str(sub))
注意,子类没有实现抽象属性__name__
,而事实上当__name__
被引用,它打印从其父“抽象” :
>>> sub.foo()
concrete
>>> sub.__name__
'abstract'
>>> print(str(sub))
concrete
然而,这不是因为__name__
是dunder方法,也不会因为某些问题@property
和@abstractmethod
装饰效果不好在一起,因为如果我雷莫从Sub
开始执行__add__
,它不允许我实例化它。 (我知道__add__
通常不是属性,但我想使用'真正的'dunder方法)如果我删除了__str__
和foo
的实现,则会出现相同的预期行为。只有__name__
表现这种方式。
这是什么导致这种行为__name__
?有没有办法解决这个问题,还是我需要让父(抽象)实现手动为我提高TypeError
?
@Keozon:检查,我很确定,因为这个类型也有一个描述符。 –
有趣。我将不得不对此进行试验。感谢您的信息! – Keozon