reflection 1

# #Reflection 
# Maps or modifies the state, properties, and methods of the program at runtime through strings. There are four methods 
def talk(self):
     print ( " %s sounds so nice.... " % self.name )
 class Proper(object):
     def  __init__ (self,name):
        self.name = name
    def eat(self):
        print("%s is eating...." % self.name)

chyice = Proper( " CaiCai " )
 # #If you want to call a certain calling method for the user, use reflection 
chyInput = input( " >>: " ).strip()
 # ##The user's input returns a string, which cannot be Directly call 
# print(hasattr(chyice,chyInput))### to determine whether the user input method exists, if it exists, return True, if it does not exist, return to Flase, and no error will be reported 
# print(getattr(chyice,chyInput))# ##Get the memory address of the corresponding method in the object of obj according to the string 
# getattr(chyice,chyInput)() 
# #So we can do this through the above two methods: 
if hasattr(chyice,chyInput):
    delattr(chyice,chyInput) # ###Delete the attribute value entered by the user 
# ################# 
    # Chy = getattr(chyice,chyInput) 
    # Chy() 
 # ## ############## 
    # setattr(chyice,chyInput,talk)#### can also be used to set attribute values ​​in methods such as input name 
else : # ##If this method does not exist We can create a new method. First, we need to define a 
    setattr(chyice,chyInput,talk) # ##Set a new attribute 
    chyice.talk(chyice) # ##The value here will not be automatically associated, so pass one by yourself value goes in 

d =chyice.name # #####setattr() 
print (d(chyice))

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325208339&siteId=291194637