Reflection
Reflection: The effect of reflection is to increase the readable line of code.
__import__ the difference between Import module and import module:
The __import__ import module is imported through a string. Import is a common method of importing modules.
4 built-in functions are commonly used for reflection: GetAttr, Hasattr, SetAttr, delattr get members, check members, set members, delete members.
Instance:
The initial module invocation is this:
# commons.pydef Login (): print (' Cool login page ') def logout (): print (' Cool Exit page ') def home (): print (' Cool homepage ') # Index.pyimport Commonsdef Run (): INP = input (' Please enter the URL to access: ') if inp = = ' Login ': commons.login () elif INP = = ' Logout ': commons.logout () elif InP = = ' Home ': commons.home () else: print (' 404 ')
After using the reflection is this:
#commons. Pydef Login (): print (' Cool login page ') def logout (): print (' Cool Exit page ') def home (): print (' Cool homepage ') # Index.pyimport Commonsdef Run (): INP = input (' Please enter the URL to access: ') # INP String Type INP = "Login" # Use the form of a string to manipulate (Find/check/delete/set) a member # delattr () # setattr () if Hasattr (Commons, INP) in an object (module): func = GetAttr (commons,inp func () else: print (' 404 ') if __name__ = = ' __main__ ': run ()
Modules can also be imported via strings:
def run (): # account/login INP = input (' Please enter URL to access: ') # INP String Type INP = "Login" # Use the form of a string to manipulate (Find/check/delete/set) the member # delattr () # setattr () m, f = inp.split ('/') obj = __import__ ( m) if hasattr (obj, f): func = getattr (obj,f) func () else: print (' 404 ') if __name__ = = ' __main __ ': run ()
For reflection subsections:
1. Import the module according to the form of the string. 2. The object (a module) is manipulated by its members in the form of a string.
Python develops "first" python-based reflection