python复习43~44魔法方法:反运算

增量赋值运算的相关魔法方法

方法作用
iadd(self,other)定义赋值加法的行为
isub(self,other)定义赋值减法的行为
imul(self,other)定义赋值乘法的行为
itruediv(self,other)定义赋值真除法的行为
ifloordiv(self,other)定义赋值整数除法的行为
imod(self,other)定义赋值取模算法的行为
idivmod(self,other)定义赋值取余算法的行为(a\\b余数)
ipow(self,other)定义当赋值幂运算**运算时的行为
ilshift(self,other)定义赋值按位左移位的行为
irshift(self,other)定义赋值按位右移位的行为
iand(other)定义赋值按位与操作的行为&
ixor(self,other)定义赋值按位异或操作的行为:^
ior(self,other)定义赋值按位或操作的行为

反运算的相关魔法方法

方法作用
radd(self,other)定义加法的行为(当左操作数不支持相应的操作是被调用)
rsub(self,other)定义减法的行为(当左操作数不支持相应的操作是被调用)
rmul(self,other)定义乘法的行为(当左操作数不支持相应的操作是被调用)
rtruediv(self,other)定义真除法的行为(当左操作数不支持相应的操作是被调用)
rfloordiv(self,other)定义整数除法的行为(当左操作数不支持相应的操作是被调用)
rmod(self,other)定义取模算法的行为(当左操作数不支持相应的操作是被调用)
rdivmod(self,other)定义当divmod()调用时的行为(a\\b余数)(当左操作数不支持相应的操作是被调用)
rpow(self,other)定义当被power()调用或**运算时的行为(当左操作数不支持相应的操作是被调用)
rlshift(self,other)定义按位左移位的行为(当左操作数不支持相应的操作是被调用)
rrshift(self,other)定义按位右移位的行为(当左操作数不支持相应的操作是被调用)
rand(other)定义按位与操作的行为&(当左操作数不支持相应的操作是被调用)
rxor(self,other)定义按位异或操作的行为:^(当左操作数不支持相应的操作是被调用)
ror(self,other)定义按位或操作的行为(当左操作数不支持相应的操作是被调用)

下面通过几个例子来熟悉一下python的这些魔法方法:

>>> class A(int):
	def __radd__(self,other):
		print('__radd__被调用了')
		return int.__add__(self,other)

	
>>> a=A(6)
>>> b=A(9)
>>> a+b
15
>>> 2+b
__radd__被调用了
11
>>> class A(int):
	def __radd__(self,other):
		print('__radd__被调用了')
		return int.__rsub__(other,self)#这里self和other的位置替换了

>>> b=A(9)
>>> 2+b
__radd__被调用了
7

定义一个类,当实例化该类是,自动判断传入了多少个参数,并显示出来。

>>> class B:
	def __init__(self,*args):#这里*表示传递多类参数,若不加*默认这里只有两个位置,而输入的占四个位置,从而出现错误,self也占一个位置
		if not args:
			print('没有传入参数')
		else:
			print('传入了%d个参数,分别是:'%len(args),end='')
			for each in args:
				print(each,end='、')

				
>>> b=B(2,6,8)
传入了3个参数,分别是:268
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值