亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 __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 關注
  • 241 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號