Cet article présente en détail les fonctions hasattr(), getattr(), setattr() et delattr() dans Python3 à travers un exemple de code. Il est très bon et a une valeur de référence. Les amis qui en ont besoin peuvent s'y référer. 🎜>
hasattr(object,name)
class People: country='China' def __init__(self,name): self.name=name def people_info(self): print('%s is xxx' %(self.name)) obj=People('aaa') print(hasattr(People,'country')) #返回值:True print('country' in People.__dict__) #返回值:True print(hasattr(obj,'people_info')) #返回值:True print(People.__dict__) ##{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10205d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
Syntaxe :
getattr(object,name,default)
class People: country='China' def __init__(self,name): self.name=name def people_info(self): print('%s is xxx' %(self.name)) obj=getattr(People,'country') print(obj) #返回值China #obj=getattr(People,'countryaaaaaa') #print(obj) #报错 # File "/getattr()函数.py", line 32, in <module> # obj=getattr(People,'countryaaaaaa') # AttributeError: type object 'People' has no attribute 'countryaaaaaa' obj=getattr(People,'countryaaaaaa',None) print(obj) #返回值None
setattr(object,name,value)
class People: country='China' def __init__(self,name): self.name=name def people_info(self): print('%s is xxx' %(self.name)) obj=People('aaa') setattr(People,'x',111) #等同于People.x=111 print(People.x) #obj.age=18 setattr(obj,'age',18) print(obj.__dict__) #{'name': 'aaa', 'age': 18} print(People.__dict__) #{'__module__': '__main__', 'country': 'China', '__init__': <function People.__init__ at 0x1007d5620>, 'people_info': <function People.people_info at 0x10215d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None, 'x': 111}
Syntaxe :
setattr(object,name)
class People: country='China' def __init__(self,name): self.name=name def people_info(self): print('%s is xxx' %(self.name)) delattr(People,'country') #等同于del People.country print(People.__dict__) {'__module__': '__main__', '__init__': <function People.__init__ at 0x1006d5620>, 'people_info': <function People.people_info at 0x10073d1e0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
class Foo: def run(self): while True: cmd=input('cmd>>: ').strip() if hasattr(self,cmd): func=getattr(self,cmd) func() def download(self): print('download....') def upload(self): print('upload...') # obj=Foo() # obj.run()
Recommandations associées :
Comment afficher le tableau numpy attributs dans la bibliothèque python3
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!