Object-oriented 5-reflection, object-oriented 5-
Hasattr (x, y) getattr (x, y) setattr (x, y, v) delattr (x, y) reflection method is to reflect the string as the memory address.
1 class people (object): 2 def _ init _ (self, name, age): 3 self. name = name 4 self. age = age 5 6 def talk (self): 7 print ('% s is talking... '% self. name) 8 p1 = people ('zsq ', 28) 9 choice = input ('Please inpute choice ') 10 11 # The current hasattr object returns True for the methods or attributes of the string name; otherwise, False is returned. # choice input name/age/talk will return True otherwise False12 if choice in ('name', 'age', 'tal'): 13 print (hasattr (p1, choice) 14 else: 15 print ('this cho Ice not in hasattr ') 16 17 # The getattr method returns the memory address of the corresponding string parameter method of the object, and can be executed by adding. # If the string is an object property, the property value is directly returned. 18 if choice in ('tal',): 19 getattr (p1, choice) () 20 elif choice in ('name', 'age '): 21 a = getattr (p1, choice) 22 print (a) 23 24 # setattr (x, 'y', v) after the setattr command calls the choice method of the object, directly call the test_setattr function. Whether or not the object has the Method 25 # After the setattr command is used to call the choice attribute of the object, the v memory address (object) or value (constant) is directly returned) 26 def test_setattr (): 27 print ('this is test setattr ') 28 29 if choice = 'talk1': 30 setattr (p1, choice, test_setattr) 31 p1.talk () 32 elif choice = 'name1': 33 setattr (p1, choice, 'name _ test') 34 print (getattr (p1, choice )) 35 # delattr Delete attributes or methods of objects 36 if choice = 'age': 37 delattr (p1, choice) 38 print (p1.age)