python3运算符重载

class MyNumber:
    def __init__(self,v):
        self.data = v
    def __repr__(self):
        return "MyNumber(%d)"%self.data
    def __add__(self,other):
        print("__add__方法被调用")
        obj = MyNumber(self.data + other.data)
        return obj
    def __sub__(self,other2):
        print("__sub__方法被调用")
        obj2 = MyNumber(self.data - other2.data)
        return obj2


n1 = MyNumber(100)
n2 = MyNumber(200)


n3 = n1 + n2  # 等同于 n3 = n1.__add__(n2)
n4 = n2 - n1
print(n3)
print(n4)

你可能感兴趣的:(python3运算符重载)