我在Python中实现了类的层次 struct .公共基类像接口一样expose 了一些方法,有一些抽象类不应该直接实例化,每个具体子类可以混合一些抽象类并提供额外的行为.例如,下面的代码是我开始的一个简单示例:
class BaseEntity(ABC):
@property
@abstractmethod
def f(self) -> List[str]:
pass
@property
@abstractmethod
def g(self) -> int:
pass
class AbstractEntity1(BaseEntity, ABC): # this should not be instantiable
@property
@abstractmethod
def f(self) -> List[str]:
return ["a", "b"]
@property
@abstractmethod
def g(self) -> int:
return 10
class AbstractEntity2(BaseEntity, ABC): # this should not be instantiable
@property
@abstractmethod
def f(self) -> List[str]:
return ["x"]
@property
@abstractmethod
def g(self) -> int:
return 3
class FinalEntity(AbstractEntity1, AbstractEntity2, BaseEntity):
@property
def f(self) -> List[str]:
return ["C"]
@property
def g(self) -> int:
return 10
我希望FinalEntity
和所有其他具体实体的行为如下:当我调用final_entity.f()
时,它应该返回["a"、"b"、"x"、"C"](因此相当于对每个Mixin和类本身调用+
操作符);类似地,当我调用final_entity.g()
时,它应该返回10 + 3 + 10
(即对每个Mixin和类本身调用+
操作符).这些函数显然只是一个示例,并不总是+
,因此必须 for each 函数定义它.
解决这个问题的最好的方法是什么?