Knowledge points-Python reflection

Source: Internet
Author: User

Intermittent from years ago to now learned object-oriented one months, before the reflection of the time, just look at the code, understanding can be, today in the code is not too handy, so Baidu all kinds, finally understand, write this blog, for introspection.

Reflection 1 What is reflection

The concept of reflection, first proposed by Smith in 1982, is a capability (introspection) that a program can access, detect, and modify its own state or behavior. The proposal of this concept soon triggered the research on the application of reflectivity in Computer science field. It is first used in the field of programming language design, and has achieved achievements in Lisp and object-oriented.

2 Python Object-oriented reflection: manipulating object-related properties in the form of a string. All things in Python are objects (you can use reflection)

Four functions that can be self-reflective the following methods apply to classes and objects (all objects, the class itself is an object)

Read the definition, or just understand, do not paste code are brush Rogue, directly on the code.

# test.py Import SYS def fn ():     Print  = fn.__name__= getattr (sys.modules[__name__], func_name)             # get the Function Object Fn_obj () according to the function name (func_name)

The operating result is:

Hello World

Take a general look at the idea,

1. First defines a function of FN

2. Reflect by getting the value of the current __name__

You are also foggy to see. Next I'll explain one by one.

Initiate

For __name__ we don't know what to understand, on the code.

#!/usr/bin/env pythondefTest ():Print('Hello world.')    Print("__name__ =",__name__)if __name__=='__main__': Test () [email protected]:~$ cat test2.pyImporttesttest.test ()

Run

[Email protected]:~$ python3 test.py Hello world. __name__ =  __main__[email protected]:~$ python3 test2.py Hello world. __name__ =  Test

From the above can be seen, directly run test __name__ is equal to the string ' __main__ ', if imported by other files at this time __name__ is equal to the module name.

Summarize:

When the module is not imported, but runs directly, then the value of __name__ is __main__. Understand the __name__.

Knowledge Points:

Sys.modules is a global dictionary that is loaded in memory when Python is started. Each time a programmer imports a new module, Sys.modules will record the modules. The dictionary sys.modules plays a role in buffering the loading module. When a module is imported for the first time, the dictionary sys.modules automatically records the module. When the module is re-imported the second time, Python will look directly into the dictionary, speeding up the program's speed.

Now that we understand __name__, we continue with the initial code analysis.

The function of introspection the following methods apply to classes and objects (everything is an object, and the class itself is an object), first look at two of them.

Hasattr (Object,name)

Determine if there is a method or property in the object that has a name string

GetAttr (object, name, Default=none)

def # known special case of GetAttr    """     GetAttr (object, name[, default]), value    Get a named attribute from an object; GetAttr (x, ' Y ') is Equival ent to x.y.    When a default argument is given, it's returned when the attribute doesn ' t    exist; without it, an exception it raised     in the case. """    Pass

# test.py Import SYS def fn ():     Print  = fn.__name__  = getattr (sys.modules[__name__], func_name)             #  based on function name (func_name), Get function Object fn_obj ()

Analysis

1. At this time equals func_name     equals    FN,__name__     equals    __main__3. sys.modules[__name_ _]   equals   # This may not be proper . 4. GetAttr (sys.modules[__name__], func_name) That is, sys.modules[__name__] takes the FN method object.
5. Fn_obj () indicates that the sys.modules[__name__] takes the FN method to implement the output

You should understand the original code at this point.

Knowledge points-Python reflection

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.