getattr、hasattr、setattr、delattr
class Foo: def __init__(self,name,age): self.n = name self.a = age def show(self): return '%s_%s' %(self.n,self.a) obj = Foo('Tom',29) func = getattr(obj,'show') #获取show方法 print(func) r = func() print(r) print(hasattr(obj,'n')) #判断obj对象是否有n这个字段 print(hasattr(obj,'a')) #判断obj对象是否有a这个字段 setattr(obj,'job','worker') #增加job字段,赋值为worker print(obj.job) delattr(obj,'a') #删除a字段
输出:
<bound method Foo.show of <__main__.Foo object at 0x0000026C049EEF60>>
Tom_29
True
True
worker