加载中...

__add__魔术方法对象重写加法运算符

对象重载__add__魔术方法

#__add__ 魔术方法  (与之相关的__radd__ 反向加法)
'''
	触发时机:使用对象进行运算相加的时候自动触发
	功能:对象运算
	参数:二个对象参数
	返回值:运算后的值
'''

'''
类似的还有如下等等(了解):
	__sub__(self, other)           定义减法的行为:-
	__mul__(self, other)           定义乘法的行为:
	__truediv__(self, other)       定义真除法的行为:/
	...
	...
'''

class MyClass():
	def __init__(self,num):
		self.num = num
		
	# 当对象在 + 号的左侧时,自动触发
	def __add__(self,other):
		# print(self)
		# print(other)
		return self.num * 3 + other
		
	def __radd__(self,other):
		# print(self)  # 对象
		# print(other) # 7
		return self.num * 5 + other
		
# add的触发方式
a = MyClass(3)
res = a + 1
print(res)

# radd的触发方式
b = MyClass(5)
res = 7 + b
print(res)

# 对象 + 对象
res = a + b
print(res)

"""
a+b 触发的是add魔术方法  self 接受的是a   other 接受的是b
return a.num + b  => return 9 + b
res =  9 + b   触发的是radd魔术方法  self 接受的是b   other 接受的是9
return b.num * 5 + 9  => 5 * 5 + 9 => 34
"""
posted @ 2024-03-17 14:52  江寒雨  阅读(46)  评论(0)    收藏  举报