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

1 投票
1 回答
746 浏览
提问于 2025-04-17 14:25

在接口中这样定义属性算不算一种好的做法呢?

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是否存在,而不会关心它是什么类型。

撰写回答