Reflection
To manipulate (Find/check/delete/set) a member (function) in the form of a string into an object (module), reflecting
Implemented with a GET method of a copy page
commons.py file
Commons.pydef login (): print ("Login page") def logout (): print ("Exit page") def Home (): print ("Main Page")
index.py file
Import Commons # call Commons Module Def run (): URL = input ("Please enter the URL to access:") "" " url== String type if url==" login " Commons.url () Obviously, this is not right, because this execution Commons will go inside him. Whether there is a URL to this function, if not, direct error to use the form of a string to the object (module) operation (Find/check/delete/ Set) member (function), Reflection "" " # SetAttr () # delattr () if hasattr (commons, URL): # url== string, and now, The URL equals a function, we enter the function, with hasattr to determine whether there is a return value of TRUE or false Func = GetAttr (commons, URL) # take this function with GetAttr, for example url== Login, so to say Now (Func==commons.login) func () # and then we'll execute the following func, which means to execute the function inside the Commons else: print (" 404 ") # if Hasattr does not check, execute this sentence 404if __name__ = = ' __main__ ': # __name__ is the current module name and the module is named __main__ when the module is run directly. This means that when the module is run directly, the following code block will be run and the code block is not run when the module is imported. run () output: Please enter the url:login login page to access
As can be seen from the above, we can only access a module, if we add a module, we need to go to import inside continue to add, of course, Python also thought about this problem, so import can also pass the string
A small test:
#文件: Commons.pydef Login (): print ("Login page") def logout (): print ("Exit page") def Home (): print ("Main Page") #文件: Import _test.pyobj = __import__ ("commons") Obj.login () obj.logout () obj.home () Output: Login page Exit Main Page
The learning path of Python Day6