标签:python def nbsp span attr class turn lam 属性
hasattr,getattr,setattr,delattr.
检查成员,获取成员,设置成员,删除成员.
class Foo(): def __init__(self): self.name = ‘wupeiqi‘ def func(self): return ‘func‘ obj = Foo() 检查是否含有成员 print(hasattr(obj,‘name‘)) #结果Ture print(hasattr(obj,‘func‘)) #结果Ture print(hasattr(obj,‘nice‘)) #结果False 获取成员 print(getattr(obj,‘name‘)) #结果wupeiqi print(getattr(obj,‘func‘)()) #结果func 设置成员 setattr(obj,‘age‘,18) print(getattr(obj,‘age‘)) #结果18 setattr(obj,‘nice‘,lambda x:x**2) print(getattr(obj,‘nice‘)(2)) #结果4 删除成员 delattr(obj,‘name‘) print(getattr(obj,‘name‘)) #报错,原因‘Foo‘对象没有属性‘name‘(‘Foo‘ object has no attribute ‘name‘) delattr(obj,‘func‘) print(getattr(obj,‘func‘)) #报错
标签:python def nbsp span attr class turn lam 属性
原文地址:https://www.cnblogs.com/chenhuping/p/9575165.html