派生类的运算符返回基类的对象是否正常?从fractions.Fraction继承时会发生这种情况
class OtherFraction(Fraction):
def __repr__(self):
return f'OtherFraction({self.numerator}, {self.denominator})'
a = OtherFraction(1, 2)
b = OtherFraction(1, 3)
c = a + b
print(repr(a), repr(b), repr(c))这张照片:OtherFraction(1, 2) OtherFraction(1, 3) Fraction(5, 6)
我原以为OtherFraction之间的数学运算会返回OtherFraction,但它会返回一个Fraction。
看起来,我可以通过重写每个操作来强制它返回OtherFraction,但这听起来是很多多余的工作。
class OtherFraction(Fraction):
def __repr__(self):
return f'OtherFraction({self.numerator}, {self.denominator})'
def __add__(self, other):
return OtherFraction(super().__add__(other))
a = OtherFraction(1, 2)
b = OtherFraction(1, 3)
c = a + b
print(repr(a), repr(b), repr(c)现在打印:OtherFraction(1, 2) OtherFraction(1, 3) OtherFraction(5, 6)
是否有任何方法使它在不手动覆盖所有操作符的情况下按预期工作?或者我期望我所描述的行为是不合理的?也许我违背了面向对象编程的重要原则,期望操作符返回派生类的对象。
发布于 2022-09-02 07:59:55
基类通常不知道派生类的存在,因此不能返回派生类的实例。我相信分数类‘是不可变的,所以它返回一个新的分数对象,而不是为add等修改现有的对象,这样就可以得到所看到的行为。
这基本上意味着,为了得到你想要的行为,你必须重写所有的数学方法。
但是,根据您想要实现的目标,继承可能不是最好的选择。
https://stackoverflow.com/questions/73578288
复制相似问题