# why write the class in the config file? # Write the class name in the config file, such as Django, add a middleware configuration, why can we call this class directly? middleware_classes = ( ' application name. Middleware.forbiddenipsmiddleware', In fact, the internal do a reflection of the operation, in middleware this module,# loaded into the Forbiddenipsmiddleware this class; # So the question comes, how do you find this class through this string? # reflection.
#echo_one.py classEchoone ():defRun (self):return '1'#echo_two.py classechotwo ():defRun (self):return '2'#echo_three.py classEchothree ():defRun (self):return '3'
#add a path to the Python interpreterImportOS, Sysbase_dir= Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__)))#Print (Os.path.abspath (__file__))#Print (Os.path.dirname (Os.path.abspath (__file__)))#print (Base_dir)#>>/home/python/desktop/echo/conf.py#>>/home/python/desktop/echo#>>/home/python/desktop # root directorysys.path.append (base_dir) Settings= { 'ret01':'Echo.class01.echo_one. Echoone', 'ret02':'Echo.class01.echo_two. Echotwo', 'ret03':'Echo.class01.echo_three. Echothree',}
fromConfImportSettings forKvinchSettings.items ():#to cycle through each class that is written in the configuration file #1. Split the string into the package path where the class is located ' | ' Class name 'Module_path, classname = V.rsplit ('.', Maxsplit=1) #2. Get the module object where the class resides Importimportlib m=importlib.import_module (Module_path)#print (m) #3. Reflect the corresponding class from the module according to the class name (the module's properties)CLS =GetAttr (M, classname)#4. Perform the methods in the class to confirm that the operation is correct Print(CLS (). Run ())
Applications for Reflection | Python