【发布时间】:2019-05-29 22:52:25
【问题描述】:
我有一个基类,其中有两个派生自它的类。我希望基类的方法表现不同,具体取决于参数是与派生类的类型相同,还是只有基类的实例但类型不同。这是当前的实现:
class MyBase:
def __init__(self, foo: int):
self.foo = foo
def __eq__(self, other):
return self.foo == other.foo
class MyDerived_1(MyBase):
def __init__(self, foo: int, bar: int):
super().__init__(foo)
self.bar = bar
class MyDerived_2(MyBase):
def __init__(self, foo: int, bar: int):
super().__init__(foo)
self.bar = bar
def __eq__(self, other):
if type(other) == type(self):
return self.bar == other.bar
elif isinstance(other, MyBase):
return super().__eq__(other)
else:
return False
在倒数第四行中,我必须明确引用 MyBase。也许这很好,但我的理解是“super”关键字的一个要点是它应该允许您更改基类而无需在类中重新编写任何内容。所以即此解决方案的一个潜在问题是,如果 MyBase 发生更改,那么 init 会很好,因为它调用“super”,但 eq 不会更新其行为。
所以我尝试用“type(super)”或“type(super())”替换“MyBase”,但这些不引用超类,它们引用对象“super”的类。
请注意,此问题不同于:
Get parent class name? Get defining class of unbound method object in Python 3 等等
因为一旦对象被初始化,他们就在寻找父类。
我想我应该能够通过运行 MRO 找到超类。但这似乎是一个糟糕的解决方案,因为我不是在寻找整个继承树,我只想知道超类的类型。
有没有办法从“超级”中提取这些信息?
【问题讨论】:
-
看起来不相关,但是为了正确的子类型化,
MyDerived_2.__eq__应该始终调用super().__eq__-self.bar上的测试应该是对super().__eq__的补充,而不是作为替代品(当然这个只有当MyDerived2应该是MyBase的正确子类型时才有意义。
标签: python inheritance super superclass