小编典典

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

all

在下面的代码中,我创建了一个基本抽象类Base。我希望所有继承自的类都Base提供该name属性,因此我将此属性设为@abstractmethod.

然后我创建了一个Base名为的子类Base_1,它旨在提供一些功能,但仍然保持抽象。中没有name属性Base_1,但是 python
instatinates 该类的对象而没有错误。如何创建抽象属性?

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')

阅读 184

收藏
2022-07-06

共1个答案

小编典典

Python
3.3
以来,修复了一个错误,这意味着property()装饰器现在在应用于抽象方法时被正确识别为抽象。

注意:订单很重要,您必须使用@property上面@abstractmethod

Python 3.3+:(
python文档):

from abc import ABC, abstractmethod

class C(ABC):
    @property
    @abstractmethod
    def my_abstract_property(self):
        ...

Python 2:python
文档

from abc import ABC, abstractproperty

class C(ABC):
    @abstractproperty
    def my_abstract_property(self):
        ...
2022-07-06