根据docs,它将@property和@ abc.abstractmethod结合使用应该有效,因此以下内容应在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]: >
In [8]: foo.greet()
Out[8]: 'hello'
所以它显然不是属性,因为它应该这样工作:
In [9]: foo.greet_comparison
Out[9]: 'hello'
也许我很愚蠢,或者根本不起作用,有人有主意吗?
解决方法:
如果您希望问候是一个属性,则仍然需要在实现中使用@property装饰器:
class Foo(FooBase):
@property
def greet(self):
return 'hello'
ABC元类所做的全部工作就是测试是否在具体类中提供了相同的名称.不管它是方法还是属性还是常规属性.
因为它不在乎,所以它也不会神奇地应用属性装饰器.这是一件好事.也许在特定的实现中,静态属性足以满足要求,而某个属性可能会显得过大.
ABC元类的目的是帮助您发现实现中的差距.它从未打算强制执行属性的类型.
请注意,在Python 3.3之前,您不能将@property与@abstractmethod结合使用.您必须改用@abstractproperty decorator.在这种情况下,当您的财产需要的不仅仅是简单的吸气剂时,就会存在歧义. Python 3.3更好地涵盖了这种情况(有关痛苦的细节,请参见issue 11610).
标签:properties,abc,python
来源: https://codeday.me/bug/20191031/1974734.html