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

标签 python function class

我正在尝试使用 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

关于python - 使用类在Python中添加两组坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19556258/

相关文章:

c - 使用 C 将用户在 main() 中输入的值传递给另一个函数

multithreading - raku 在具有不同参数的线程中调用相同的函数

java - 从父类类型方法返回子对象

c - 为什么这个 C 函数什么都不做?

Python Pandas : Stack and Enumerate Date to Create New Records

python - 合并字典列表,同时合并相似 ke 的值

python - 如何在 django 中强制出现异常以便在 django 中对其进行测试

objective-c - 当我们只能使用 NSObject 时,为什么还要使用 id?

java - 在另一个类中使用一个类的实例是否算作依赖或关联?

python - 使用 JPype - 如何访问 JDBC 元数据函数