如何在python抽象类中创build抽象属性

在下面的代码中,我创build了一个基本的抽象类Base 。 我想要从Baseinheritance的所有类提供name属性,所以我使这个属性成为@abstractmethod

然后我创build了一个名为Base_1Base类的子类,它提供了一些function,但仍然是抽象的。 在Base_1没有name属性,但是python会在Base_1创build一个没有错误的对象。 如何创build抽象属性?

 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之前 ,你不能嵌套@abstractmethod@abstractmethod

使用@abstractproperty创build抽象属性( docs )。

 from abc import ABCMeta, abstractmethod, abstractproperty class Base(object): # ... @abstractproperty def name(self): pass 

代码现在提出了正确的例外:

回溯(最近一次通话最后):
  文件“foo.py”,第36行,在 
     b1 = Base_1('abc')  
 TypeError:不能用抽象方法名实例化抽象类Base_1