030 reflection,
### Reflection
# Getattr, hasattr, setattr, and delattr are related to fields in the class. For details, refer to the example.
#1 class Person: def _ init _ (self, name, age): self. name = name self. age = age def show_lover (self): print ('lover ') o = Person ('x', 21) B = 'name' print (o. _ dict _ [B]) #2 B = input ('>') if hasattr (o, B): v = getattr (o, B) # Get the delattr (o, B) setattr (o, 'age', 21) print (v) func = getattr (o, 'show _ lover ') # obtain method func ()View Code
#3 obtain the fields of the Class Object
class Person: stat = '123' def __init__(self,name,age): self.name = name self.age = ager = getattr(Person,'stat')print(r)
#4 obtain functions and fields of other modules
# s.pyNAME = '_nbloser'def func(): return'func'class Person: def __init__(self):self.name = '_nbloser'
# Execution. pyimport sr1 = getattr (s, 'name') r2 = getattr (s, 'func') Pers = getattr (s, 'person') p1 = Pers () print (r1, r2 (), p1.name) # _ nbloser func _ nbloser
# Application example
Def f1 (): return 'homepage 'def f2 (): return 'News' def f3 (): return' extract 'import sinp = input ('> ') if hasattr (s, indium): func = getattr (s, indium) print (func () else: print (404)