在下面的代码中,我创建了一个基本抽象类Base
。我希望从Base
继承的所有类都提供name
属性,因此我将此属性设置为@abstractmethod
。
然后我创建了Base
的一个子类,称为Base_1
,它旨在提供一些功能,但仍然是抽象的。在Base_1
中没有name
属性,但是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一个bug被修复,这意味着
property()
decorator在应用于抽象方法时现在被正确地标识为抽象。注意:顺序很重要,您必须在
@abstractmethod
之前使用@property
Python 3.3+:(python docs):
Python2:(python docs)
基于上面詹姆斯的回答
把它当装饰用
在Python 3.3之前,不能嵌套
@abstractmethod
和@property
。使用
@abstractproperty
创建抽象属性(docs)。代码现在引发正确的异常:
相关问题 更多 >
编程相关推荐