Reflection definition: Through string mapping or modifying the state, properties, methods of the program runtime.
There are 4 ways to do this:
1:getattr (Object,name,default=none): Gets the memory address of the corresponding method in the Obj object based on the string, and returns the value directly if it is a property.
2:hasattr (Object,name): Method mapping that determines whether a name string exists in object
3:setattr (x,y,v) = = "X.y = V: Sets a new property by a string (you can reset the normal property value, or you can set the function to a class method)
4:delattr (x, y)
Example:
1 #This method is dynamically loaded into the class for invocation2 defBulk (self):3 Print('%s is yelling ...'%self.name)4 5 classDog (object):6 def __init__(self,name):7Self.name =name8 defEat (Self,food):9 Print('%s is eat%s'%(Self.name,food))Ten Oneobj = Dog ('Shar') AMess = input ('Please enter a method for the operation:') - ifhasattr (obj,mess): - #-----Delete--- the #delattr (obj,mess) # Impersonation incoming name, removing the Name property - #print (obj.name) # error message No Name attribute - #-----Print the method value as a string--- - #Fun = GetAttr (obj,mess) # here will get the memory address of the talk method through GetAttr + #Fun (' Baba ') - #-----Reset Property Values--- + #setattr (obj,mess, ' 22 ') # Here you can re-modify an existing property value A #Print (GetAttr (obj,mess)) at Else: - - #------Setting introduces functions outside the class into the class---- - #SetAttr (obj,mess,bulk) # dynamically loads the bulk function into the class - #GetAttr (obj,mess) # dynamically uses the GetAttr method to get the input value, and then passes the Obj object itself as a parameter because the bulk function above has a self parameter. - in #-----Setting Dynamic Incoming Properties -SetAttr (obj,mess,22)#Set the default property value, to Print(GetAttr (obj,mess))#return default property value + #property values that already exist can be reset
View Code
Python--Reflection