gpt4 book ai didi

python - 在二维向量类中覆盖 __mul__ 以保持交换性

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

我定义了以下类:

class Point(object):

def __repr__(self):
return "("+str(self.x)+","+str(self.y)+")"

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

def __add__(self, point):
return Point(self.x+point.x,self.y+point.y)

def __sub__(self, point):
return Point(self.x-point.x,self.y-point.y)

def __mul__(self, num):
return Point(num*self.x,num*self.y)

def length(self):
return (self.x**2 + self.y**2)**.5

下面的代码有效:

x = Point(1,2)
y = Point(1,3)
print x+y
print (y+x)
print (x-y)
print (y-x)
print y*3

输出:

(2,5)
(2,5)
(0,-1)
(0,1)
(3,9)

但这不是:

print 3*y

它给出了以下错误:

----> 1 print 3*y
TypeError: unsupported operand type(s) for *: 'int' and 'Point'

这是因为点类被输入到 int mul 函数中,我假设。我怎样才能保留 Point 类中包含的点的定义,并且仍然让 3*y 返回与 y*3 相同的值?

最佳答案

3 * y 

我们在左侧有一个 int 实例,在右侧有一个 Point 实例。 Point 不是 int 的子类。在这种情况下,int.__mul__ 类在这个操作中获得了第一个机会,而 Point.__mul__ 在这件事上没有发言权。

你必须在你的类上实现 Point.__rmul__ 来处理这种情况。

关于python - 在二维向量类中覆盖 __mul__ 以保持交换性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41512646/

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