码迷,mamicode.com
首页 > 其他好文 > 详细

__bool__ | __add__ | __len__ 魔术方法

时间:2019-05-25 00:10:00      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:attr   self   complex   with   pre   __add__   bool   att   fun   

# ###__bool__ 魔术方法
‘‘‘
	触发时机:使用bool(对象)的时候自动触发
	功能:强转对象
	参数:一个self接受当前对象
	返回值:必须是布尔类型
‘‘‘
‘‘‘
类似的还有如下等等(了解):
	__complex__(self)      被complex强转对象时调用
	__int__(self)          被int强转对象时调用
	__float__(self)        被float强转对象时调用
	...
	...
‘‘‘
class MyBool():
	def __bool__(self):
		print(122)
		# return True
		return False
		
obj = MyBool()
res = bool(obj)
print(res)

#__add__ 魔术方法  (与之相关的__radd__ 反向加法)
‘‘‘
	触发时机:使用对象进行运算相加的时候自动触发
	功能:对象运算
	参数:二个对象参数
	返回值:运算后的值
‘‘‘
‘‘‘
类似的还有如下等等(了解):
	__sub__(self, other)           定义减法的行为:-
	__mul__(self, other)           定义乘法的行为:
	__truediv__(self, other)       定义真除法的行为:/
	...
	...
‘‘‘
class MyAdd():
	def __init__(self,num):
		self.num = num
	
	# 对象+数值,并且对象在+加号的左边,自动触发__add__方法
	def __add__(self,other):
		#self.num  => 3 + 56 => 59
		return self.num + other
		
	def __radd__(self,other):
		# self 接受b, other 接受33
		return self.num + other * 10

# 1.当对象在加号的左侧  自动触发add 方法	
a = MyAdd(3)
res = a+56
print(res)


# 2.当对象在加号的右侧  自动触发radd 方法
b = MyAdd(5)
res = 33 + b
print(res)

# 3 a+b =?
res = a+b
print(res)

‘‘‘
a在加号的左侧,触发add魔术方法
self.num + other => 3 + b

b在加号的右侧,触发radd魔术方法
res = 3+b
self.num + other * 10 => 5 + 3 *10 => 35

‘‘‘

# ###__len__ 魔术方法
print("<===>")
‘‘‘
	触发时机:使用len(对象)的时候自动触发 
	功能:用于检测对象中或者类中某个内容的个数
	参数:一个self接受当前对象
	返回值:必须返回整型
‘‘‘
# 用len(对象)方式,算出该对象所归属的类有多少自定义成员
class MyLen():
	pty1 = 1
	pty2 = 2
	__pty3 = 3
	
	def func1():
		pass
		
	def func2():
		pass
		
	def __func3():
		pass
	def __func4():
		pass
		
	def __func5():
		pass
	
	def __len__(self):
		# print(MyLen.__dict__)
		dic = MyLen.__dict__
		lst = [i for i in dic if not( i.startswith("__") and i.endswith("__"))  ]
		num = len(lst)
		return num

obj = MyLen()
res = len(obj)
print(res)
"""
{‘__module__‘: ‘__main__‘, 
‘pty1‘: 1, ‘pty2‘: 2,
 ‘_MyLen__pty3‘: 3, 
 ‘func1‘: <function MyLen.func1 at 0x7f10880d9620>, ‘func2‘: <function MyLen.func2 at 0x7f10880d96a8>,
 ‘_MyLen__func3‘: <function MyLen.__func3 at 0x7f10880d9730>, ‘__len__‘: <function MyLen.__len__ at 0x7f10880d97b8>,
 ‘__dict__‘: <attribute ‘__dict__‘ of ‘MyLen‘ objects>, 
 ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘MyLen‘ objects>, ‘__doc__‘: None}
"""

  

__bool__ | __add__ | __len__ 魔术方法

标签:attr   self   complex   with   pre   __add__   bool   att   fun   

原文地址:https://www.cnblogs.com/huangjiangyong/p/10920659.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!