Abstract attribute (not property)?

前端 未结 7 955
心在旅途
心在旅途 2020-11-30 22:41

What\'s the best practice to define an abstract instance attribute, but not as a property?

I would like to write something like:

class AbstractFoo(me         


        
7条回答
  •  一整个雨季
    2020-11-30 23:26

    Just because you define it as an abstractproperty on the abstract base class doesn't mean you have to make a property on the subclass.

    e.g. you can:

    In [1]: from abc import ABCMeta, abstractproperty
    
    In [2]: class X(metaclass=ABCMeta):
       ...:     @abstractproperty
       ...:     def required(self):
       ...:         raise NotImplementedError
       ...:
    
    In [3]: class Y(X):
       ...:     required = True
       ...:
    
    In [4]: Y()
    Out[4]: <__main__.Y at 0x10ae0d390>
    

    If you want to initialise the value in __init__ you can do this:

    In [5]: class Z(X):
       ...:     required = None
       ...:     def __init__(self, value):
       ...:         self.required = value
       ...:
    
    In [6]: Z(value=3)
    Out[6]: <__main__.Z at 0x10ae15a20>
    

    Since Python 3.3 abstractproperty is deprecated. So Python 3 users should use the following instead:

    from abc import ABCMeta, abstractmethod
    
    class X(metaclass=ABCMeta):
        @property
        @abstractmethod
        def required(self):
            raise NotImplementedError
    

提交回复
热议问题