1, Reflection
In Python, reflection refers to manipulating the properties of an object through a string, involving the use of four built-in functions
hasattr(): judge whether the object contains the function or data corresponding to the string
getattr(): get the corresponding variable name or function name according to the string
setattr(): sets the key value pair (the name of the namespace) for the object according to the string
delattr(): delete the key value pair (the name of the namespace) corresponding to the object according to the string
In Python, all objects, classes and objects can use the following four methods
It is very simple to implement reflection in python. During the running of the program, if we get an object that does not know what attributes exist, if we want to operate its internal attributes, we can first obtain the attribute list of any class or object through the built-in function dir, which is all in string format
class People: def __init__(self,name,age,gender): self.name=name self.age=age self.gender=gender obj=People('egon',18,'male') dir(obj) # The properties viewed in the list are all strings [......,'age', 'gender', 'name']
The next step is to find a way to manipulate the attributes of objects through strings, which involves the use of built-in functions hasattr, getattr, setattr and delattr (everything in Python is an object, and the following four methods can be used for classes and objects)
class Teacher: def __init__(self,full_name): self.full_name =full_name t=Teacher('jason Lin') # hasattr(object,'name') hasattr(t,'full_name') # Press string 'full'_ Name 'judge whether there is attribute t.full_name # getattr(object, 'name', default=None) getattr(t,'full_name',None) # Equivalent to t.full_name, if the attribute does not exist, the default value of None is returned # setattr(x, 'y', v) setattr(t,'age',18) # Equivalent to t.age=18 # delattr(x, 'y') delattr(t,'age') # Equivalent to del t.age
Reflection instance
class Wincmd: def ls(self): print('windows running -----ls') def dir(self): print('windows running -----dif') class Linuxcmd: def ls(self): print('Linux running -----ls') def dir(self): print('Linux running -----dif') def run(obj): while True: cmd = input('your command:').strip() if hasattr(obj,cmd): func_name = getattr(obj,cmd) func_name() break else: print('cmd command not found') break win = Wincmd() lin = Linuxcmd() if __name__ == '__main__': run(win)
2, Magic method
Magic method is actually a method that automatically triggers execution under certain conditions. The general structure is __ xxxx _ _, Double underlined method
Python's Class mechanism has built-in many special methods to help users highly customize their own classes. These built-in methods start and end with double underscores and will be triggered automatically when certain conditions are met. We use the commonly used methods__ str__ And__ del__ As an example to briefly introduce their use
__ str__ Method will be triggered automatically when the object is printed. The print function prints its return value. We usually customize the print information of the object based on the method, which must return the string type
class People: def __init__(self,name,age): self.name=name self.age=age def __str__(self): return '<Name:%s Age:%s>' %(self.name,self.age) #Return type must be a string p=People('lili',18) print(p) # Trigger P__ str__ (), print the returned value # <Name:lili Age:18>
__ del__ Automatically triggered when the object is deleted. Since Python's built-in garbage collection mechanism will automatically clean up the resources of Python programs, there is no need to customize objects when an object only occupies application level resources__ del__ Method, but when the generation of an object involves the application of system resources (such as files opened by the system, network connections, etc.), Python's garbage collection mechanism is useless for the recycling of system resources. We need to customize this method for the object to automatically trigger the recycling of system resources when the object is deleted
class People: def __init__(self,name,age): self.name=name self.age=age def __del__(self): print("=======>") obj = People('fuank',19) del obj # When the object obj is deleted, the obj is automatically triggered__ del__ () print('end') """ =======> end """
class People: def __init__(self,name,age): self.name=name self.age=age def __del__(self): print("=======>") obj = People('fuank',19) print('end') # The garbage collection mechanism will automatically delete obj and trigger del obj """ end =======> """
Common magic methods supplement
__ getattr__ : Automatically triggered when the object does not have a name
__ setattr__ : Object automatically triggers > > > obj when adding attributes Variable name = variable value
__ call__ : Automatically triggered when an object is called with parentheses
Introduction to reference metaclass ---- > Metaclass
__enter__ :
The object is automatically triggered when the with context management syntax is executed
The variable name after as will get what the method returns
__ exit__ : The object is automatically triggered after the execution of the with context management syntax
__ getattribute__ : This method is executed whenever the object looks for the name, whether or not the name exists
If there are__ getattribute__ Method, then it will not be executed__ getattr__ method