The path to Python experts [10] reflection of python basics and the path to python
Simple reflection --> is to use a string to operate (search, check, delete, and set) members in an object (module.
Requirement: the user enters a module name. The module name is imported into the file:
1: All files are imported in the same directory.
Create two files in the same directory: index. py, commons. py
The content of the commons. py file is as follows:
def f1(): return "F1"def f2(): return 'f2'
Write code in the index. py file:
M = input ('input module: ') module = _ import _ (m) # module is equivalent to print (module. f1 (), an alias in the form of import modulename as f ())
Use _ import _ ('module name') to import the module! Why is this method used to import modules without using import modulename? Because the user inputs all strings, while the import modulename method, modulename is not a string!
In this case, execute the index. py file to import the module normally and receive the return values in the f1 function:
Requirement: The preceding module is imported when the user inputs the module name. Now, the user needs to input the function name again, and then execute the corresponding function in the module in the file.
M = input ('input module: ') # user input module name f = input ('input func name :') # user input function name module = _ import _ (m) # import user input module func = getattr (module, f) # Call the user input function print (func ())
If the commons module and the index. py file are not imported in the same directory: If the commons. py file is under lib/commons. py
Module = _ import _ ('lib. '+ m, fromlist = True) # import the user input module
Appendix:
Getattr (object, name): gets a specified member from a specified module.
Hasattr (object, name): determines whether a specified member exists in a specified module.
Delattr (object, name): deletes a specified member from a specified module! The original file is not affected, but is deleted in memory.
Setattr (object, name, value): Add a member to the specified module! Does not affect the original file, but increases in memory