How to create abstract properties in python abstract classes

后端 未结 3 1404
独厮守ぢ
独厮守ぢ 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:49

    Until Python 3.3, you cannot nest @abstractmethod and @property.

    Use @abstractproperty to create abstract properties (docs).

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

    The code now raises the correct exception:

    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
    

提交回复
热议问题