gpt4 book ai didi

python - 更改自定义类中 __add__、__mul__ 等方法的操作顺序

转载 作者:太空狗 更新时间:2023-10-29 22:15:27 27 4
gpt4 key购买 nike

我有一个矢量类:

class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return '(%s,%s)' % (self.x, self.y)
def __add__(self, n):
if isinstance(n, (int, long, float)):
return Vector(self.x+n, self.y+n)
elif isinstance(n, Vector):
return Vector(self.x+n.x, self.y+n.y)

效果很好,即我可以写:

a = Vector(1,2)
print(a + 1) # prints (2,3)

但是如果操作顺序颠倒,则失败:

a = Vector(1,2)
print(1 + a) # raises TypeError: unsupported operand type(s)
# for +: 'int' and 'instance'

我理解错误:将int对象添加到Vector对象是未定义的,因为我没有在int中定义它> 类。有没有办法在不在 int(或 int 的父级)类中定义它的情况下解决这个问题?

最佳答案

你还需要定义__radd__

有些操作不一定像这样计算 a + b == b + a,这就是 Python 定义 addradd 方法的原因。

更好地解释自己:它支持这样一个事实,即“int”没有定义 + 操作,其中 class Vector 实例作为操作的一部分。因此 vector + 1 与 1 + vector 不同。

当 Python 试图查看 1.__add__ 方法可以做什么时,会引发异常。 Python 会寻找 Vector.__radd__ 操作来尝试完成它。

在 OP 的情况下,评估为 true 并且满足 __radd__ = __add__

class Vector(object):

def __init__(self, x, y):
self.x, self.y = x, y

def __str__(self):
return '(%s,%s)' % (self.x, self.y)

def __add__(self, n):
if isinstance(n, (int, long, float)):
return Vector(self.x+n, self.y+n)
elif isinstance(n, Vector):
return Vector(self.x+n.x, self.y+n.y)

__radd__ = __add__


a = Vector(1, 2)
print(1 + a)

哪些输出:

(2,3)

这同样适用于所有类似数字的操作。

关于python - 更改自定义类中 __add__、__mul__ 等方法的操作顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34827132/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com