Skip to main content
 首页 » 编程设计

python之使用类在Python中添加两组坐标

2025年05月04日14yxwkf

我正在尝试使用 Python 中的类添加两组坐标。这是我目前所拥有的。

class Position: 
    def __init__(self, x, y): 
        self.x = x 
        self.y = y 
 
    def add(self, x): 
        self.x = self + x 

然后在不同的程序中运行我的类(class)

A = Position(1, 1) 
B = Position(2, 3) 
A.add(B) 
A.print() 

所以我试图将 A 和 B 相加得到 (3,4)。我将如何使用添加类来做到这一点?我不知道要为参数设置什么或在函数体中放入什么才能使其工作。谢谢

请您参考如下方法:

转换为

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

也就是说,使用不可变对象(immutable对象)通常很有用,所以为什么不让 add 返回一个新的 Position

def add(self, other): 
    return Position(self.x + other.x, self.y + other.y) 

那么如果你真的想变得时髦,为什么不覆盖 __add__()

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

这样您就可以使用“+”运算符将两个点相加。

a = Position(1, 1)  
b = Position(2, 3)  
c = a + b