Python Development Skills required (5)

Source: Internet
Author: User
Tags reflection vars

Python reflection mechanism

I remember when I learned Java, I came into contact with the concept of reflection, and then with the work, often hear the concept of reflection, today decided to sum up a good.

The following 3 blog posts I feel very good to write, you can make reference.

71406953

Http://www.mamicode.com/info-detail-1401422.html

Https://www.cnblogs.com/huxi/archive/2011/01/02/1924317.html

First, you need to know the concept of reflection, the comparison of classical interpretation is divided into the following categories:

    • To find or manipulate properties inside an object by means of a string called reflection
    • A State, property, or method that is called reflection by a string mapping or modifying a program's runtime
    • Reflection is the manipulation of object-related members in the form of strings, and the essence of reflection is actually the use of strings to manipulate (Find/Get/delete/Add) members in the form of a string, a string-based event-driven!

in Python everything is object, so you can use reflection .

The reflection feature in Python involves four built-in functions: Hasattr, GetAttr, SetAttr, delattr, and these four functions are used for internal execution of the object: check if it contains a

Has a member, gets a member, sets a member, deletes a member.

Example Program 1: Two ways to access members: obj. and obj.__dict__[' members ']

#!/usr/bin/python#-*-coding:utf-8-*-class Student (object):    def __init__ (self,name,age):        self.name = name        Self.age = Age    def study (self,name):        print ('%s is studing '%self.name) student = Student (' Angela ', +) print (student.__dict__)  #查看student的成员属性 (Member of the namespace) print (VARs (student))     #查看student的成员属性 (the member that corresponds to the namespace) #通过字符串直接访问对象所对应的成员. Print (student. __dict__[' name '],student.__dict__[' age ') print (Student.__dict__.get (' name ')) print (Student.__dict__.get (' age ')) #当然, we're usually like this, but that's the way it's basically print (student.name,student.age)

Operation Result:

{' name ': ' Angela ', ' Age ': 25} {' name ': ' Angela ', ' age ': 25}angela 25angela25angela 25Process finished with exit code 0

 

the reflection in Python involves four main methods :

Hasattr (OBJ,NAME_STR): Determines whether the object obj contains a method named Name_str or a static property, the return value is a Boolean value, that is, the form of a string to determine the

Whether a property is contained within the image.

GetAttr (OBJ,NAME_STR): Based on the string name_str to get the memory address of the corresponding function in the object obj or the value corresponding to the static property, if the return value is a function

memory address that needs to be added in parentheses to be called.

SetAttr (Obj,name_str,value): Adds or modifies the value of a property or method named Name_str in the Obj object.

Delattr (OBJ,NAME_STR): Removes the property named Name_str in the Obj object.

Example program: Four methods for reflection in Python

#!/usr/bin/python#-*-coding:utf-8-*-class Student (object):    def __init__ (self,name,age):        self.name = name        Self.age = Age    def study (self,name):        print ('%s is studing '%self.name) student = Student (' Angela ', +) print (student.__dict__)  #查看student的成员属性 (the member that corresponds to the namespace) #检查对象是否含有某个成员. Print (hasattr (student, ' name ')) print (Hasattr (student, ' study ')) # Gets the numeric value of a member of an object through a string. Func = getattr (student, ' study ') print (func) func (student) #通过字符串设置或增加对象当中某个成员的数值setattr ( Student, ' name ', ' Jack ') setattr (student, ' salary ', ') print (student.__dict__) #通过字符串删除对象当中的某个成员. Delattr (Student, ' Name ') delattr (student, ' salary ') print (student.__dict__) #设置成员的时候还可以增加方法成员. SetAttr (student, ' show ', Lambda num:num+1 ) Print (VARs (student))

Operation Result:

{' name ': ' Angela ', ' Age ': 25} Truetrue<bound method Student.study of <__main__. Student object at 0x000000000219d400>>angela is studing{' salary ': $, ' name ': ' Jack ', ' age ': 25}{' age ': 25}{' show ': <function <lambda> at 0x0000000001e5cbf8> "Age": 25}process finished with exit code 0

  

Example program: In Python, everything is object, so as long as the object, you can use reflection.

What the accout.py contains:

#!/usr/bin/python#-*-coding:utf-8-*-import sys# in Python, everything is object: As long as the object, you can use the reflection mechanism. Class Person (object):    def __ Init__ (self,name,age):        self.name = name        Self.age = Age    def eat (self,name):        print ('%s is eating '% Self.name) If __name__ = = ' __main__ ':    #获取当前的模块对象, and gets the value corresponding to the module object.    Module_name = sys.modules[__name__]    print (module_name.__dict__)

visit.py What to do:

#!/usr/bin/python#-*-coding:utf-8-*-import accountif hasattr (account, "person"):    student = getattr (account, ' Person ') (' Angela ', ')    print (student.__dict__)    if hasattr (student, ' eat '):        func = getattr (student, ' eat ') )        func (Student)

Operation Result:

{' Age ': +, ' name ': ' Angela '}angela is eatingprocess finished with exit code 0

  

Application Scenarios for reflection:

In the program, if we want to use a string variable var to import a module or a method under a module, this time directly execute import VAR will be an error

, because Var is a variable in the program, and it is not feasible to invoke a function called the same name by a string variable, which is required to use the reflection.

Depending on the URL entered by the user, different functions are called to implement different operations, that is, the functionality of a Web URL router, which is one of the core components in the Web framework.

Example Program 1: First, there is a Commons module, which has several functions, which are used to display different pages, the code is as follows:

#!/usr/bin/python#-*-coding:utf-8-*-def Login ():    print (' This is a landing page! ') def logout ():    print (' This is an exit page! ') Def home ():    print (' This is the main page of the site. ')

Subsequently, there is a visit module, through which the module can log on to different pages (the simple version of the program), if not used to reflect, most people may write:

#!/usr/bin/python#-*-coding:utf-8-*-import commonsdef Run ():    INP = input (' Please enter the URL of the page you want to access: '). Strip ()    If INP = = ' Login ':        commons.login ()    elif INP = = ' Logout ':        commons.logout ()    elif InP = = ' Home ':        Commons.home ()    else:        print (' 404 ') if __name__ = = ' __main__ ':    run ()

Examples of running results:

Please enter the page you want to visit Url:login this is a landing page! Process finished with exit code 0

If you can use reflection, we can write this (everything objects)

Import Commonsdef Run ():    INP = input (' Please enter the URL of the page you want to access: '). Strip ()    if Hasattr (COMMONS,INP):        func = GetAttr ( COMMONS,INP)        func ()    else:        print (' 404 ') if __name__ = = ' __main__ ':    run ()

  

Example Program 2: We are simulating an example of FTP, in fact, the truth is the same, in Python, everything is the object, as long as the object, you can use reflection .

#!/usr/bin/python#-*-coding:utf-8-*-class ftp_client (object):    def __init__ (self,host):        self.host = Host        print (' Connecting machine: ', host, ' ... ')    def run (self): when        True: line            = input (' Please enter the command you want to operate: '). Strip ()            cmd = line.split () [0]            file_name = Line.split () [1]            if Hasattr (self,cmd):                func = getattr (self,cmd)                Print (func)                func (file_name)            else:                print (' The instruction you entered does not exist. ')    def get (self,filename):        print (' Downloading file%s, wait ... '%filename) ftp_client = ftp_client (' 127.0.0.1 ') Ftp_client.run ()

Operation Result:

Connecting machine: 127.0.0.1 .... Please enter the command you need to operate: Get Word.txt<bound method Ftp_client.get of <__main__. Ftp_client object at 0x00000000024f9a20>> is downloading file word.txt, wait ... Please enter the command you need to do: put word.txt the instruction you entered does not exist. Enter the command you want to use:

  

Example Program 3: The reflection mechanism is also often used in the collaborative development process.

Suppose there's a man now. A: Developing an interface, authorization interface: Grant.

#!/usr/bin/python#-*-coding:utf-8-*-class Ugdap (object):    def __init__ (self,db_name,table_name):        self.db_ Name = db_name        self.table_name = table_name    # DEF grant (self):    #     "" "    #     : return: The interface is under development ... # "" "    #     print (' Licensing in progress ')

As the calling interface, I'm not sure if the interface has been developed, so I can write:

#!/usr/bin/python#-*-Coding:utf-8-*-from commons Import ugdapugdap_obj = Ugdap (' FDM ', ' exe_cool_data_operate ') if Hasattr (ugdap_obj, ' Grant '):    func = getattr (ugdap_obj, ' Grant ')    print (func)    func () Else:    print ( ' Unable to get interface information, skip this step. ')

  

The meaning of reflection:

Maybe someone would ask Python not have two built-in functions exec and eval? They are also able to execute strings. Like what:

12345 exec("print(‘haha‘)")结果:haha

Why not just use them? Why bother using getattr,__import__ so hard?

In fact, in the example above, the core topic around is how to use strings to drive different events, such as importing modules, calling functions, and so on, these are Python reflector machines

System, is a programming method, the embodiment of the design pattern, condensed the high cohesion, loose coupling programming idea, cannot simply use the execution string to replace. Of course, exec and Eval also have it

Stage, which is also often used in web frameworks.

Python Development Skills required (5)

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.