Reflection, mapping to object properties by string
?
Class people:country= ' China ' def __init__ (self,name,age): Self.name=name self.age=age def talk (sel f): Print ('%s is talking '%self.name) p = people ("GD", page) print (p.name) # p.__dic__[' name ']print (p.talk) # <bou nd method People.talk of <__main__. People an object at 0x00000000027b7470>>print (Hasattr (p, ' name ')) # True to determine if the object p has a name attribute, hasattr (), the first argument to the object, and the second argument Pass Property name Print (Hasattr (p, ' Talk1 ')) # Trueprint (GetAttr (p, ' name ')) # GD Gets the attribute in object P # print (GetAttr (p, ' name2 ')) # Attribu Teerror: ' People ' object has no attribute ' name2 ' # getattr (), there is no corresponding attribute when, will error, we can pass in the third parameter print (GetAttr (p, ' name2 ', None)) # None so that when the property is not found, it will return None setattr (p, ' sex ', ' Machine Master ') print (p.sex) # machine master print (p.__dict__) # {' Name ': ' GD ', ' age ': 22, ' Sex ': ' Machine Master '}delattr (p, ' sex ') # Delete property print (p.__dict__) # {' Name ': ' GD ', ' age ': 22}# hasattr () getattr () Setatter () d Elattr () applies not only to objects, but also to class print (Hasattr (people, ' Country ')) # Trueprint (GetAttr (People, ' Country ')) # China
?
?
Application of Reflection
class Service: def run(self): while True: cmd = input(">>:").strip() if hasattr(self, cmd): func = getattr(self, cmd) func() def get(self): print('get......') def put(self): print('put.....')obj = Service()obj.run()# >>:get# get......# >>:put# put.....
python-Object-oriented 05 reflection