abc.abstractmethod +属性 [英] abc.abstractmethod + property
问题描述
根据 docs ,它应该可以结合使用 @property
和 @ abc.abstractmethod
,因此以下内容应在python3.3中起作用:
According to the docs it should work to combine @property
and @abc.abstractmethod
so the following should work in python3.3:
import abc
class FooBase(metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def greet(self):
""" must be implemented in order to instantiate """
pass
@property
def greet_comparison(self):
""" must be implemented in order to instantiate """
return 'hello'
class Foo(FooBase):
def greet(self):
return 'hello'
测试实现:
In [6]: foo = Foo()
In [7]: foo.greet
Out[7]: <bound method Foo.greet of <__main__.Foo object at 0x7f935a971f10>>
In [8]: foo.greet()
Out[8]: 'hello'
因此它显然不是属性,因为它应该这样工作:
so it is obviously not a property, because then it should work like that:
In [9]: foo.greet_comparison
Out[9]: 'hello'
也许我'm愚蠢或根本行不通,有人知道吗?
Maybe I'm to stupid or it simply doesn't work, somebody has an idea?
推荐答案
如果要问候
成为属性,您仍然需要在实现中使用 @property
装饰器:
If you want greet
to be a property, you still need to use the @property
decorator in your implementation:
class Foo(FooBase):
@property
def greet(self):
return 'hello'
ABC元类所做的全部工作就是测试您是否在具体类中提供了相同的名称;
All that an ABC metaclass does is test wether or not you have provided the same name in the concrete class; it doesn't care if it is a method or a property or a regular attribute.
因为它不在乎,所以不会神奇地应用属性
装饰器。这是一件好的事情;也许在特定的实现中,静态属性足以满足要求,并且属性可能会过大。
Because it doesn't care, it doesn't magically apply property
decorators either. This is a good thing; perhaps in a specific implementation a static attribute is enough to satisfy the requirement, and a property would be overkill.
ABC元类的目的是帮助您检测出差距。您的实施;
The purpose of a ABC metaclass is to help you detect gaps in your implementation; it never was intended to enforce the types of the attributes.
请注意,在Python 3.3之前,您不能合并 @property
和 @抽象方法
。您必须使用 @abstractproperty
装饰器来代替。在这种情况下,当您的财产需要的不仅仅是简单的吸气剂时,就会存在歧义。 Python 3.3更好地涵盖了这种情况(有关痛苦的细节,请参见问题11610 )。
Note that before Python 3.3 you can not combine a @property
with an @abstractmethod
. You would have to use an @abstractproperty
decorator instead. There is an ambiguity there when your property needs more than a simple getter in that case; Python 3.3 covers that case much better (see issue 11610 for the painful details).
这篇关于abc.abstractmethod +属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!