为了账号安全,请及时绑定邮箱和手机立即绑定

使用 __add__ 方法相加

使用 __add__ 方法相加

Helenr 2023-12-29 15:06:51
我目前正在研究一个创建球并为它们提供位置的课程。我想为类创建一个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 + ball3print (ball4)代码现在的工作方式并不符合预期。我希望 ball1 + ball3 位置相加,但我得到的打印结果如下:[3, 4][5, 8][4, 4][3, 4, 4, 4]我们将 ball1 和 ball3 的 x 和 y 值并排放置,而不是相加。
查看完整描述

4 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

当您将两个列表添加在一起时,它只是简单地附加。您的添加需要如下所示:

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


查看完整回答
反对 回复 2023-12-29
?
月关宝盒

TA贡献1772条经验 获得超5个赞

使用数组时,“+”运算符连接两个操作数中的元素并返回一个新数组。所以plus并没有按照你想象的那样做。

您必须开发另一个函数来对数组的每个成员求和并返回这个新数组


查看完整回答
反对 回复 2023-12-29
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

这是因为您在 2 个 python 列表之间使用求和运算符,这将连接两个列表。如果你想按元素求和,你必须这样做:


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

我还建议您查看numpy库,它将提供您想要的数学运算符。在这种情况下,您的类可以重写为:


import numpy as np


class Ball:

    def __init__ (self, x, y):

        self.position = np.array([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 = 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]


查看完整回答
反对 回复 2023-12-29
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

通过列表理解单独添加项目并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, b3 in zip(ball1.position, ball3.position)]

print (ball4)


[3, 4]

[5, 8]

[4, 4]

[7, 8]

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


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


查看完整回答
反对 回复 2023-12-29
  • 4 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信