Skip to main content
 首页 » 编程设计

Python 在对相同对象执行相同操作两次时给出了两个不同的结果

2025年05月04日15emanlee

我在 python 中创建了一个类 vector2D,其中包含一个添加向量的方法。然后我用它两次添加相同的向量并得到不同的结果。为什么会这样?

代码如下:

class vector2D: 
    def __init__(self, x, y): 
        self.x = x 
        self.y = y 
 
    def __add__(self, other): 
        self.x += other.x 
        self.y += other.y 
        return self.x, self.y    
 
#Creating vector objects 
v1 = vector2D(2, 3) 
v2 = vector2D(4, 8) 
 
#using the redefined addition operator to add vector objects 
v = v1 + v2       #output: (6, 11) 
print(v) 
 
#Adding again 
v = v1 + v2      #output: (10, 19) 
print(v) 

请您参考如下方法:

你们都将向量添加到位并返回结果!

    def __add__(self, other): 
        self.x += other.x 
        self.y += other.y 
        return self.x, self.y    

这改变了第一个向量的参数! += 表示 self.x = self.x + other.x。

改为这样做:

    def __add__(self, other): 
        result_x = self.x + other.x 
        result_y = self.y + other.y 
        return result_x, result_y