在 Python 接口中定义属性是个好主意吗?



这样的接口中定义属性是一种好的做法吗?

class MyInterface(object):
    def required_method(self):
        raise NotImplementedError
    @property
    def required_property(self):
        raise NotImplementedError

我会使用ABC类,但是是的;你甚至可以为这个用例使用@abstractproperty

from abc import ABCMeta, abstractproperty, abstractmethod
class MyInterface(object):
    __metaclass__ = ABCMeta
    @abstractmethod
    def required_method(self):
        pass
    @abstractproperty
    def required_property(self):
        pass

ABC的子类仍然可以自由地实现required_property作为属性;ABC只会验证required_property的存在,而不是它是什么类型。

最新更新