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

问题描述:

在下面的代码中,我创建了一个基本抽象类Base。我想要从Base继承的所有类提供name属性,所以我将此属性设置为@abstractmethod如何在python抽象类中创建抽象属性

然后我创建了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') 
+0

疑难杂症:如果你忘了'类C'使用装饰'@ property','name'将恢复的方法。 – kevinarpe 2014-11-02 05:35:09

由于Python 3.3一个错误是固定意味着property()装饰当施加到一个抽象方法现在正确地识别为抽象。

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 
+28

实际上这个答案对于年轻的python来说是错误的:从3.3开始,'@ abstractproperty'被弃用,赞成像OP这样的组合。 – 2012-11-09 20:18:36

+10

从3.3文档:http://docs.python.org/3/library/abc.html#abc.abstractproperty – codeape 2012-11-12 08:40:51

+0

谢谢,codeape。我会相应地更新答案。 – 2012-11-12 13:45:45