9, the five-reflection module

Source: Internet
Author: User

If we need to call a function by judging a string in our code, we can use if, else to operate, if there are 100 functions, if there are 1000 functions.

At this time, with reflection, say it. The simple way to do this is to use a string to manipulate (find) a member in an object (module).

def login ():    print (' Cool login page ') def logout ():    print (' Cool Exit page ') def home ():    print (' Cool homepage ') def run ():    INP = input (' Please enter the URL to access ') if    hasattr (NOTE,INP): #判断note这个模块中有没有以inp变量内容为名字的函数, if you enter login, it is to determine if there is a login function        Func = GetAttr (NOTE,INP) #获取这函数        func ()     else:         print (' 404 ') if __name__ = = ' __main__ ':     run ()

Import the module as a string:

obj = __import__ ("Commons")   

  

  

  

9, the five-reflection module

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.