4 回答

TA貢獻1828條經驗 獲得超3個贊
當您將兩個列表添加在一起時,它只是簡單地附加。您的添加需要如下所示:
def __add__ (self, other): return [self.position[0]+other.position[0], self.position[1]+other.position[1]]

TA貢獻1772條經驗 獲得超5個贊
使用數組時,“+”運算符連接兩個操作數中的元素并返回一個新數組。所以plus并沒有按照你想象的那樣做。
您必須開發另一個函數來對數組的每個成員求和并返回這個新數組

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]

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)]
添加回答
舉報