Defines a reflection to manipulate its members according to the form of a string
Before I know about reflection, I'll look at the built-in method __import__, remember this built-in method?
- __import__ for importing modules as strings
INP = input (' Please enter the module you want to import:'__import__(INP) #Import XML as Mokuaiprint(Mokuai. __doc__)
- GetAttr is used to search for functions in a module as a string
Import= input (' Please enter the method you want to perform under Re:'= getattr (re,str_func) Print # Print the memory address of the function found
Reflection Members
- GetAttr is used to search for functions in a module as a string
Import= input (' Please enter the method you want to perform under Re:'= getattr (re,str_func,none) # found on the return function, did not find on the return none, not set none, no error found Print # Print the memory address of the function found
- Hasattr a module to see if there is something in the form of a string
Import= hasattr (Re,'match')print= hasattr (re ,'fjfijajfojg')print(Ret2)
R = Hasattr (Commons,'age')print(r) #False SetAttr (Commons,'age',Lambda a:a + 1= GetAttr (Commons,' age ') # no error ret = R (1)print(ret)
Example: Routing system for web framework
from Import = input (' Please enter URL:'= url.split ('/') [-1 ]if hasattr (ACCOUNT,INP): = getattr (ACCOUNT,INP) func () Else : Print ('404')
url = input ('Please enter a URL:') Target_module,target_func= Url.split ('/') M=__import__('lib.'+target_module,fromlist=True)ifhasattr (m,target_func): Tar_func=GetAttr (m,target_func) R=Tar_func ()Print(R)Else: Print('404')
You are welcome to ask questions and questions about my blog content! Thanks
Author: Pat Province Mr.
Python Basics-Seventh-7.3 Reflections