The reflection functionality in Python is provided by the following four built-in functions: Hasattr, GetAttr, SetAttr, delattr, and four functions for internal execution of objects: Check for a member, get a member, set a member, delete a member.
#commons.py Filename="Nick" defF1 ():return "This is F1." defF2 ():return "This is F2." defnb ():return "This is niubily." #index.py FileImportCommons#to look for something in a module based on a string.Target_func = GetAttr (Commons,"F1")#Find a functionresult =Target_func ()Print(Result) Target_func= GetAttr (Commons,"name")#Find Global VariablesPrint(target_func) Target_func= GetAttr (Commons," Age", None)#no returned none foundPrint(Target_func)#to determine whether something exists in a module based on a stringTarhas_func = Hasattr (Commons,"f5")#Find a functionPrint("Before:", Tarhas_func)#Tarhas_func = Hasattr (commons, "name") # Find global Variables#print (Tarhas_func) #to set something in a module as a stringSetAttr (Commons,"f5","Lambda x:return \ "This is new func.\"")#set a functionSetAttr (Commons," Age", 18)#Setting Global VariablesTarhas_func= Hasattr (Commons,"f5")#Check if a function existsPrint("After :", Tarhas_func)#to remove something from a module in the form of a stringDelattr (Commons,"f5")#Delete a functionTarhas_func= Hasattr (Commons,"f5")#Check if a function existsPrint("End:", Tarhas_func)
Object instance
classFoo:def __init__(self,name,age): Self.name=name Self.age= AgedefShow (self):Print("gets the method of the function") obj=foo ('2018 World Cup', 2018) #hasattr whether a field existsPrint(Hasattr (obj,'name'))#GetAttr getting InformationGetname=getattr (obj,'name')Print(GetName)#setattr Assignment ValueSetAttr (obj,' Time','2018-6-16')Print(obj.time)#delattr DeleteDelattr (obj,'name')Print(Obj.name)#error attributeerror after deletion: ' Foo ' object has no attribute ' name '
Python ———— Reflection mechanism