Applications for Reflection | Python

Source: Internet
Author: User

# 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.