Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add two instances of my class

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)+")"
like image 731
user4704979 Avatar asked Feb 10 '23 14:02

user4704979


1 Answers

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)
like image 174
A.J. Uppal Avatar answered Feb 19 '23 14:02

A.J. Uppal