使用__add__方法进行加法

问题描述

我目前正在研究一个创建球并给其定位的类。我想对类做一个 add 方法,该方法将两个球的位置加在一起。我正在使用的代码是:

class Ball:
    def __init__ (self,x,y):
        self.position = [x,y]
    def __add__ (self,other):
        return self.position + other.position
    
ball1 = Ball(3,4)
print (ball1.position)
ball2 = Ball(5,8)
print (ball2.position)
ball3 = Ball(4,4)
print (ball3.position)
ball4 = ball1 + ball3
print (ball4)

当前代码的工作方式与预期不符。我希望将ball1 + ball3的位置相加,但是得到的打印结果是这样的:

[3,4]
[5,8]
[4,4]
[3,4,4]

我们将ball1和ball3的x和y值并排放置,而不是相加。

解决方法

将两个列表加在一起时,它只会追加。 您的添加内容应如下所示:

def __add__ (self,other):
    return [self.position[0]+other.position[0],self.position[1]+other.position[1]]
,

分别使用列表理解和zip使用以下项分别添加项目:

[b1 + b3 for b1,b3 in zip(ball1.position,ball3.position)]

class Ball:
    def __init__ (self,x,y):
        self.position = [x,y]
    def __add__ (self,other):
        return self.position + other.position

ball1 = Ball(3,4)
print (ball1.position)
ball2 = Ball(5,8)
print (ball2.position)
ball3 = Ball(4,4)
print (ball3.position)
ball4 = [b1 + b3 for b1,ball3.position)]
print (ball4)

[3,4]
[5,8]
[4,4]
[7,8]

编辑:您可以将列表理解进一步简化为:

ball4 = [sum(b) for b in zip(ball1.position,ball3.position)]
,

使用数组时,“ +”运算符将两个操作数中的元素联接在一起并返回一个新数组。所以加号并没有按照您的想法做。

您必须开发另一个函数,该函数求和数组的每个成员并返回此新数组。

,

那是因为您在2个python列表之间使用sum运算符,它将两个列表串联在一起。如果要按元素总结元素,则必须采用以下方式:

return [self.x+other.x,self.y+other.y]

我还建议您查看 numpy 库,该库将为您提供所需的数学运算符。在这种情况下,您的班级可以改写为:

import numpy as np

class Ball:
    def __init__ (self,y):
        self.position = np.array([x,y])
    def __add__ (self,other):
        return self.position + other.position
    
ball1 = Ball(3,4)
print (ball3.position)
ball4 = ball1 + ball3
print (ball4)

结果:

>>> ball1 = Ball(3,4)
>>> print (ball1.position)
[3 4]
>>> ball2 = Ball(5,8)
>>> print (ball2.position)
[5 8]
>>> ball3 = Ball(4,4)
>>> print (ball3.position)
[4 4]
>>> ball4 = ball1 + ball3
>>> print (ball4)
[7 8]