在Python接口中定义属性是否是个好主意?
在接口中这样定义属性算不算一种好的做法呢?
class MyInterface(object):
def required_method(self):
raise NotImplementedError
@property
def required_property(self):
raise NotImplementedError
1 个回答
4
我会使用一个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
是否存在,而不会关心它是什么类型。