我想要添加到我的班级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)+")"
答案 0 :(得分:5)
您必须为您的班级实施__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)