How to create abstract properties in python abstract classes

后端 未结 3 1398
独厮守ぢ
独厮守ぢ 2020-12-04 16:15

In the following code, I create a base abstract class Base. I want all the classes that inherit from Base to provide the name property

3条回答
  •  日久生厌
    2020-12-04 16:29

    Since Python 3.3 a bug was fixed meaning the property() decorator is now correctly identified as abstract when applied to an abstract method.

    Note: Order matters, you have to use @property before @abstractmethod

    Python 3.3+: (python docs):

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

    Python 2: (python docs)

    class C(ABC):
        @abstractproperty
        def my_abstract_property(self):
            ...
    

提交回复
热议问题