代码点读机 / Python / __add__

__add__ Python · 特殊方法

定义对象用 + 号相加时的行为。

怎么用

def __add__(self, 其他):

小例子

class 钱包:
    def __init__(self, m):
        self.m = m
    def __add__(self, other):
        return 钱包(self.m + other.m)
print((钱包(10) + 钱包(20)).m)

运行结果

30

官方文档:https://docs.python.org/zh-cn/3/reference/datamodel.html#object.__add__

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条