实现算术运算¶
我们希望实现计算,因此,混合模式操作要么调用一个作者知道参数类型的实现,要么转变成为最接近的内置类型并对这个执行操作。对于子类 Integral,这意味着 __add__() 和 __radd__() 必须用如下方式定义:
class MyIntegral(Integral):
def __add__(self, other):
if isinstance(other, MyIntegral):
return do_my_adding_stuff(self, other)
elif isinstance(other, OtherTypeIKnowAbout):
return do_my_other_adding_stuff(self, other)
else:
return NotImplemented
def __radd__(self, other):
if isinstance(other, MyIntegral):
return do_my_adding_stuff(other, self)
elif isinstance(other, OtherTypeIKnowAbout):
return do_my_other_adding_stuff(other, self)
elif isinstance(other, Integral):
return int(other) + int(self)
elif isinstance(other, Real):
return float(other) + float(self)
elif isinstance(other, Complex):
return complex(other) + complex(self)
else:
return NotImplemented
Complex 有 5 种不同的混合类型的操作。 我将上面提到的所有代码作为“模板”称作 MyIntegral 和 OtherTypeIKnowAbout。 a 是 Complex 的子类型 A 的实例 (a : A |