假设我想定义一个新的 number 类。比如,RationalFractions 或 GaussIntegers,随便什么。当然,我可以很容易地为MyClass的两个对象定义a+b。但我希望能够添加 MyClass 的对象,其中包含一些现有的对象,例如“整数”或“ float ”。结果具有相关类型(从我的角度来看)。例如。 GaussInteger + float = GaussInteger、RationalFraction + integer = RationalFraction 等的结果。 我想我应该以某种方式改变 add 为 Object 类,或“integer”,“float”?或者有一种方法可以在不干扰现有类的情况下做到这一点?
编辑。所以,举个例子:
class RatFr:
def __init__(self, m, n=1):
self.m = m
self.n = n
def __add__(self, other):
temp = (RatFr(other) if type(other) == int else other)
return RatFr(self.m * temp.n + self.n * temp.m, self.n * temp.n)
def __str__(self):
return f'{self.m}/{self.n}'
a = RatFr(5,3)
b = 1
print(a)
print(a + b)
print(b + a)
结果是:
5/3
8/3
Traceback (most recent call last):
File "/Users/aleksej/PycharmProjects/Alex2/playaround.py", line 19, in <module>
print(b + a)
TypeError: unsupported operand type(s) for +: 'int' and 'RatFr'
试图改变 self 没有任何好处。一旦第一个操作数是 int,python 显然会寻找整数相加方法。
请您参考如下方法:
是的。您将希望从对象覆盖 __add__,将 self 和 x 作为参数。然后,您可以根据其类型处理 x。在这里你有几个选择。您可以进行显式类型检查,但这不是很 Pythonic。我可能会制作一个转换函数,将 int、float 等转换为您的类型,并在 x 上调用它。然后你可以在你的类型的两个对象之间做任何加法。这种在执行操作之前对转换函数的调用是在后端的 mpmath 库中完成的。请记住,您需要检查要转换的内容是否已经是正确的类型。
