1

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

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

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

在另一个程序中运行我的课程

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

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

4

4 回答 4

10

将添加转换为

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

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

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
于 2013-10-24T03:17:05.420 回答
2

你想要这样的东西:

class Position(object):

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

    def __add__(self, other):
       "Add two Positions and return a new one."
       return Position(self.x + other.x, self.y + other.y)   

    __radd__ = __add__

    def __iadd__(self, other):
       "In-place add += updates the current instance."
       self.x += other.x
       self.y += other.y
       return self

    def __str__(self):
       "Define the textual representation of a Position"
       return "Position(x=%d, y=%d)" % (self.x, self.y)

   __repr__ = __str__

现在Position可以使用常规 Python 运算符添加您的类并使用常规语句+打印:print

A = Position(1, 2)
B = Position(2, 3)
A += B
print(A)
于 2013-10-24T03:23:04.930 回答
0

好吧,我不完全确定你真的想改变你的观点。如果你想改变你的观点,我会做

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

或者,更常见的是(对于职位,我会说,你想获得一个新职位)

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

这样,如果你覆盖__eq__

Position(1,2) + Position(3,4) == Position(4,6)
于 2013-10-24T03:19:49.427 回答
0

您可能只想import numpy使用numpy.array而不是滚动自己的Position课程。

于 2013-10-24T04:11:46.010 回答