重写__len__函数对象魔术方法

### __len__魔术方法

'''
触发时机:使用len(对象)的时候自动触发
功能:用于检测对象中或者类中某个内容的个数
参数:一个self接受当前对象
返回值:必须返回整型
'''

len(对象) => 类中的所有自定义成员

class MyClass():
pty1 = 1
pty2 = 2
__pty3 = 3

def func1():
	pass
def func2():
	pass
def __func3():
	pass
	
def __len__(self):
	# 以__开头并且以__结尾的成员过滤掉;
	return len( [  i for i in MyClass.__dict__ if not (  i.startswith("__") and i.endswith("__")  )  ] ) 

obj = MyClass()
print(len(obj))

"""
代码原型;
print(MyClass.dict)
lst = []
for i in MyClass.dict:
print(i , type(i))
if not ( i.startswith("") and i.endswith("") ):
lst.append(i)
print(len(lst))
"""

"""

抛离系统自带的魔术方法
{
'module': 'main',
'pty1': 1,
'pty2': 2,
'_MyClass__pty3': 3,
'func1': <function MyClass.func1 at 0x7f6898431378>,
'func2': <function MyClass.func2 at 0x7f6898431400>,
'_MyClass__func3': <function MyClass.__func3 at 0x7f6898431488>,
'len': <function MyClass.len at 0x7f6898431510>,
'dict': <attribute 'dict' of 'MyClass' objects>,
'weakref': <attribute 'weakref' of 'MyClass' objects>,
'doc': None
}
"""

posted @   江寒雨  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示
主题色彩