python - 添加我的类的两个实例

标签 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)+")"

最佳答案

你必须为你的类实现一个__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/

相关文章:

c++ - 从文件中读取值并使用类

c# - 由于其保护级别而无法访问结构

qt - 访问另一个 Qt Designer 表单类的 ui 元素

python - 使用 super() 和使用 self 从父类调用方法有什么区别?

python - 如何获取函数输出的多个值

python - 有谁知道如何根据txt文件将网格返回到shell中?

python - 比较大列表中的项目 - 查找长度相差 1 个字母的项目 - Python

python - Ubuntu 上的 Flask 无法找到 Flask.json

.net - 非 IDisposable 接口(interface)的 IDisposable 实现

python |实例化前的类方法装饰器