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)
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)
本文介绍了一个名为MyNumber的自定义类,该类实现了运算符重载功能,包括加法和减法操作。通过这个例子展示了如何在Python中为自定义对象定义特殊方法以实现特定的功能。

被折叠的 条评论
为什么被折叠?



