use*_*437 0 python class function
我正在尝试使用python中的类添加两组坐标.这就是我到目前为止所拥有的.
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
def add(self, x):
self.x = self + x
Run Code Online (Sandbox Code Playgroud)
并在一个不同的程序中运行我的课程
A = Position(1, 1)
B = Position(2, 3)
A.add(B)
A.print()
Run Code Online (Sandbox Code Playgroud)
所以我试图添加A和B来获得(3,4).我如何使用add类做到这一点?我不知道要为参数设置什么或者在函数体中放置什么以使其工作.谢谢
转换添加为
def add(self, other):
self.x = self.x + other.x
self.y = self.y + other.y
Run Code Online (Sandbox Code Playgroud)
也就是说,使用不可变对象通常很有用,所以为什么不添加返回一个新位置
def add(self, other):
return Position(self.x + other.x, self.y + other.y)
Run Code Online (Sandbox Code Playgroud)
然后,如果你真的想要变得时髦,为什么不覆盖 __add__()
def __add__(self, other):
return Position(self.x + other.x, self.y + other.y)
Run Code Online (Sandbox Code Playgroud)
这将允许您使用"+"运算符一起添加两个点.
a = Position(1, 1)
b = Position(2, 3)
c = a + b
Run Code Online (Sandbox Code Playgroud)