0x00 Preface
defF1 ():Print('F1')defF2 ():Print('F2')deff3 ():Print('f3')deff4 ():Print('f4') A= 1
test.py
Import test as SSSS.F1 () ss.f2 () Print (SS.A)
We are going to import another module, we can use import. Now there is such a requirement, I dynamically input a module name, you can always access to the import module in the method or variable, how to do?
IMP = input ("Please enter the module name you want to import:" )__import__(imp) This way is to import the module you want to import by importing the string cc.f1 () # F1 methods in the execution module
Above we implemented the dynamic input module name, allowing us to enter the module name and execute the function inside. But one drawback is that the function being executed is fixed. So, can we improve on the dynamic input function name and execute it?
# dynamic.pyimp = input (" Please enter module:"__import__(imp) # equivalent to import impInp_func = input (" Please enter the function to be executed:"= GetAttr (Dd,inp_func,none) #作用: Find the function inp_func you need to call from the import module, and return a reference to the function. It's annoying if you don't find it. NONEF () # Execute the function
We implemented the above, dynamically import a module, and dynamically enter the function name and then perform the corresponding function.
There is, of course, a little bit of a problem: My module name may not be stored in this level directory. There may be a way to store it:
So how do we fix this? Look at the following code:
__import__ ("lib.text.commons") __import__ ("lib.text.commons", fromlist = True) #改用这种方式就能导入成功 # Equivalent to import configinp_func = input (" Enter the function to execute:"= GetAttr (DD, Inp_func) F ()
0x01 reflection mechanism
The above says so much, in the end what is the reflection mechanism?
In fact, the reflection is to import the module through the form of a string, and in the form of a string, the module looks for the specified function and executes it. Use the form of a string to manipulate (Find/Get/delete/Add) members in an object (module), a string-based event driver!
Let's introduce four built-in functions:
1. The getattr () function is the core function of Python introspection, which is used in the following general context:classA:def __init__(self): Self.name='zhangjing'#self.age= 'defmethod (self):Print"Method Print"Instance=A ()PrintGetAttr (Instance,'name,' notFind'#如果Instance object has the attribute name prints the value of the Self.name, otherwise the print' notFind'PrintGetAttr (Instance,' Age','Not find')#If there is an attribute in the instance object, age prints the value of self.age, otherwise print ' not find 'PrintGetAttr (A,'Method','default')#If there is a method, print its address, otherwise print the defaultPrintGetAttr (A,'Method','default')()#If there is a method, run the function and print none otherwise print default2. hasattr (object, Name) Description: Determines whether the object contains an attribute named name (Hasattr is implemented by calling GetAttr (Ojbect, name) to throw an exception)3. SetAttr (object, name, value) This is the relative getattr (). A parameter is an object, a string, and an arbitrary value. The string may list an existing property or a new property. This function assigns the value to the property. The object allows it to be provided. For example, SetAttr (x, "Foobar",123) equivalent to X.foobar = 123. 4. delattr (object, name) a set of functions related to SetAttr (). Parameters are made up of an object (remember that everything in Python is an object) and a string. The string argument must be one of the object property names. The function deletes a property specified by string for the obj. Delattr (x,'Foobar')=delX.foobar
We can use the above four functions to perform a series of operations on the module.
r = hasattr (commons,xxx) determines whether a function or variable exists in print(r) SetAttr (Commons,'age Add a global variable to the Commons module age =, create a successful return Nonesetattr (config,'age ',Lambda a:a+1) // Add a function to the module Delattr (Commons,' age')//delete a variable or function in the module
Note: getattr,hasattr,setattr,delattr changes to the module are made in memory and do not affect the actual content in the file.
0x02 instances
Simulation of web framework routing based on reflection mechanism
Requirements: For example, we enter: WWW.XXX.COM/COMMONS/F1, return the results of F1.
#dynamically import the module and execute its functionurl = input ("URL:") Target_module, Target_func= Url.split ('/') M=__import__('lib.'+target_module, fromlist=True) InP= Url.split ("/") [-1]#split the URL and remove the last string from the URLifHasattr (M,target_func):#determine if there is a string of INP in the Commons moduleTarget_func = GetAttr (M,target_func)#get references to INPTarget_func ()#ExecutionElse: Print("404")
Reference
Python reflection mechanism of Python face test questions