我想像这样添加到我的类 Bar
的实例中:
x = Bar([5, 12, 5])
y = Bar([4, 5, 6])
x+y #Bar([9, 17, 11])
这是类:
class Bar:
def __init__(self, arr):
self.items = arr
def __repr__(self):
return "Bar("+str(self.items)+")"
最佳答案
你必须为你的类实现一个__add__
方法:
def __add__(self, new):
newlst = [];
for i, j in zip(self.items, new.items):
newlst.append(i+j)
return Bar(newlst)
因此:
>>> x = Bar([5, 12, 5])
>>> y = Bar([4, 5, 6])
>>> x+y
Bar([9, 17, 11])
class Bar:
def __init__(self, arr):
self.items = arr
def __repr__(self):
return "Bar("+str(self.items)+")"
def __add__(self, new):
newlst = [];
for i, j in zip(self.items, new.items):
newlst.append(i+j)
return Bar(newlst)
关于python - 添加我的类的两个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29220581/