I want to add to instances of my class Bar
as such:
x = Bar([5, 12, 5])
y = Bar([4, 5, 6])
x+y #Bar([9, 17, 11])
Here is the class:
class Bar:
def __init__(self, arr):
self.items = arr
def __repr__(self):
return "Bar("+str(self.items)+")"
You have to implement an __add__
method for your class:
def __add__(self, new):
newlst = [];
for i, j in zip(self.items, new.items):
newlst.append(i+j)
return Bar(newlst)
As such:
>>> 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With