添加我的班级的两个实例

时间:2015-03-23 21:17:36

标签: python class oop instance add

我想要添加到我的班级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)+")"

1 个答案:

答案 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)