在下面的代码中,我创建了一个基本抽象类Base
。我希望从Base
继承的所有类都提供name
属性,所以我将这个属性设为@abstractmethod
。
然后我创建了一个Base
的子类,名为Base_1
,它旨在提供一些功能,但仍然是抽象的。在name
中没有Base_1
属性,但是python在没有错误的情况下设置了该类的对象。如何创建抽象属性?
from abc import ABCMeta, abstractmethod
class Base(object):
__metaclass__ = ABCMeta
def __init__(self, strDirConfig):
self.strDirConfig = strDirConfig
@abstractmethod
def _doStuff(self, signals):
pass
@property
@abstractmethod
def name(self):
#this property will be supplied by the inheriting classes
#individually
pass
class Base_1(Base):
__metaclass__ = ABCMeta
# this class does not provide the name property, should raise an error
def __init__(self, strDirConfig):
super(Base_1, self).__init__(strDirConfig)
def _doStuff(self, signals):
print 'Base_1 does stuff'
class C(Base_1):
@property
def name(self):
return 'class C'
if __name__ == '__main__':
b1 = Base_1('abc')
由于Python 3.3修复了一个错误,因此当应用于抽象方法时,property()
装饰器现在被正确识别为抽象。
注意:顺序很重要,你必须在@property
之前使用@abstractmethod
来自python docs:
class C(ABC):
@property
@abstractmethod
def my_abstract_property(self):
...
直到Python 3.3,你不能嵌套@abstractmethod
和@property
。
使用@abstractproperty
创建抽象属性(docs)。
from abc import ABCMeta, abstractmethod, abstractproperty
class Base(object):
# ...
@abstractproperty
def name(self):
pass
代码现在引发了正确的异常:
Traceback (most recent call last): File "foo.py", line 36, in b1 = Base_1('abc') TypeError: Can't instantiate abstract class Base_1 with abstract methods name