#动态添加属性 import types class Person(object): country = 'china' def __init__(self,name): self.name=name #动态删除属性和方法 #del #delattr p1=Person('zhiliao') print(p1.name) # del p1.name delattr(p1,name) print(p1.name) #动态添加实例方法 @staticmethod def run(): print('正在奔跑') Person.run=run Person.run() #动态添加类方法 @classmethod def run(cls): print('%s 在奔跑'%cls.country) Person.run=run Person.run() #动态添加实例方法 def run(self): print('{} 在奔跑'.format(self.name)) p1=Person(name='zhiliao') p1.run=types.MethodType(run,p1) p1.run() #动态添加属性 p=Person('zhiliao') p.age=18 print(p.age) #setattr # setattr(p,'age',18) print(p.age) print(p.__dict__) # print(p.__class__) # print(p.__dir__()) print(p.__init__('cyy')) print(p.__dict__) print(hasattr(p,'name')) if hasattr(p,'name'): print('True') else: print('false')
为类动态添加属性和方法
最新推荐文章于 2023-12-12 14:58:48 发布