Python Basics-Seventh-7.3 Reflections

Source: Internet
Author: User

Defines a reflection to manipulate its members according to the form of a string

Before I know about reflection, I'll look at the built-in method __import__, remember this built-in method?

    • __import__ for importing modules as strings
INP = input (' Please enter the module you want to import:'__import__(INP)  #Import XML as Mokuaiprint(Mokuai.  __doc__)
    • GetAttr is used to search for functions in a module as a string
Import= input (' Please enter the method you want to perform under Re:'= getattr (re,str_func) Print # Print the memory address of the function found
Reflection Members
    • GetAttr is used to search for functions in a module as a string
Import= input (' Please enter the method you want to perform under Re:'= getattr (re,str_func,none)  # found on the return function, did not find on the return none, not set none, no error found Print # Print the memory address of the function found
    • Hasattr a module to see if there is something in the form of a string
Import= hasattr (Re,'match')print= hasattr (re ,'fjfijajfojg')print(Ret2)
    • SetAttr Settings
R = Hasattr (Commons,'age')print(r)  #False SetAttr (Commons,'age',Lambda a:a + 1= GetAttr (Commons,'  age ')  # no error ret = R (1)print(ret)
    • Delattr Delete

Example: Routing system for web framework
 from Import  = input (' Please enter URL:'= url.split ('/') [-1 ]if  hasattr (ACCOUNT,INP):    = getattr (ACCOUNT,INP)    func () Else :     Print ('404')

url = input ('Please enter a URL:') Target_module,target_func= Url.split ('/') M=__import__('lib.'+target_module,fromlist=True)ifhasattr (m,target_func): Tar_func=GetAttr (m,target_func) R=Tar_func ()Print(R)Else:    Print('404')

You are welcome to ask questions and questions about my blog content! Thanks

Author: Pat Province Mr.

Python Basics-Seventh-7.3 Reflections

Related Article

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.