Reflection in Python

Source: Internet
Author: User

In most languages, there is a reflection mechanism. In effect, reflection is to increase the dynamic description ability of the program. Popular is the decision that allows users to participate in code execution. At the time of program writing, we will write many classes, the classes have their own functions, objects and so on. These classes and functions are designed to post code services, and programmers decide when to use which class and when to invoke a function. But most of the time, we need to decide which block of code to execute based on the user's needs. The user may send instructions by clicking, entering data, or by other means, and reflection passes the user's instructions to the block of code that needs to be executed. This process is performed automatically, without the need to manually check whether the user instruction should execute that piece of code, but rather by the reflection mechanism to automatically find the code block for that execution. Most reflections are illustrated by the Web, and the most common usage scenarios for reflection itself are actually invoking different functions based on the URL of the web. Here, of course, we don't have to discuss his specific application, just a brief description of his use.

The

        Python's reflection mechanism is simple, with a total of four key functions: GetAttr, Hasattr, SetAttr, delattr, respectively. The first two are most commonly used, and the last one is rarely used. The reflection defined by Python itself refers to the manipulation of certain elements in the container, not just the classes, but also functions, objects, which are different when looking for objects, except that they look for the object itself, and the class that creates the object is searched. To illustrate the specific role of reflection in Python using practical examples, look at the requirements first. In all languages, we can easily make the user enter a data, and then print that data, this is the simplest human-computer interaction. The implementation process in the code is to generate a variable, get the user input data, assign a value to the variable. Print variables. In the same way we can define two functions in a class, then ask the user to enter data, according to the data entered by the user to decide which function to execute, this is an artificial reflection mechanism. We can use If--else to judge when there are only two functions that need to be looked up. But if there are more than hundreds of data, the repetitive use of if is not only inefficient, but also hard to measure the amount of code. In this case, reflection is needed. The specific code is as follows:

#新建一个方法类 named Echo_test class in the code below, define three functions, function content for the print functions of the name __author__ = "Lixin" Def Echo_test1 ():    print ("Echo_test1") def Echo_ Test2 ():    print ("Echo_test2") def echo_test3 ():    print ("Echo_test3") #另一个执行类 code as follows __author__ = "Lixin" #import Echo_test Import Method Class Func_name = input ("What does want to Do?,please enter:") #请求用户输入数据func = GetAttr (echo_test,func_name) #调用g etattr function, the parameters are the class name of the method class, the data entered by the user. The generate variable receives the return parameter func () #把变量当做方法执行 # The output results are as follows/library/frameworks/python.framework/versions/3.5/bin/python3.5/users/ Penglong/documents/python/s11/day8/echo_example/echo_func.pywhat want to Do?,please enter:echo_test1# input data echo _test1# execution results process finished with exit code 0

  

To analyze the code, first of all, the code is only an example, very imperfect, and the input data can only be defined function name, but we mainly discuss the role of GetAttr. From the code it is easy to see that it takes a class name and a string as arguments, and then goes to the class to find the same function name as the string, and returns the entire contents of that function. So, our variable is actually a function, so it can be called directly. This is a simple, complete reflection. It is also the most important feature of reflection in Python. The role of Hasatter is more for getattr services. As in the above code, it is possible for the user to enter data that does not match the function name in our defined function, and it cannot be executed. If there is no error defense mechanism, the program will crash, so get the data entered by the user, before you go directly to find the execution, you need to determine whether the user wants to execute the function of existence, this is the function of hasattr code as follows:

#在上一份代码的基础上直接更改, note is in the interaction class Func_name = input ("What does want to Do?,please enter:") func = Hasattr (echo_test,func_name) # GetAttr to Hasatterprint (func) output is as follows:/library/frameworks/python.framework/versions/3.5/bin/python3.5/users/ Penglong/documents/python/s11/day8/echo_example/echo_func.pywhat does want to do?,please Enter:echo_test1True # Returns the result as a Boolean process finished with exit code 0

  

Above, it can be seen that the parameters of the HASATTR function are the same as the GetAttr, receiving a class and a string, returning a Boolean value. Its role is to detect whether the user input content has a corresponding function exists. If there is, returns True, No, false. We can prevent the errors of the function from being found based on the results. Therefore, it is often used with getattr, if the decision exists, then gets and executes, which guarantees that the code will not run in error. The role of SetAttr is to create an object with the following code:

#还是在原代码基础上修改, interactive class print (Dir (echo_test)) #首先输出一下echo_test这个类的所有方法func_name = input ("What does want to do?,please enter:" ) #请求用户输入数据func = SetAttr (Echo_test,func_name,lambda x:x+1) #调用setattr函数, parameters are class name, user input data, a simple function print (dir (echo_test)) #再次打印echo_test这个类的所有方法 "" Output results in the first print class method result [' __author__ ', ' __builtins__ ', ' __cached__ ', ' __doc__ ', ' __file__ ', ' __  Loader__ ', ' __name__ ', ' __package__ ', ' __spec__ ', ' echo_test1 ', ' echo_test2 ', ' echo_test3 '] what does the want to do?,please Enter:lixin Second print results [' __author__ ', ' __builtins__ ', ' __cached__ ', ' __doc__ ', ' __file__ ', ' __loader__ ', ' __name__ ', ' __ package__ ', ' __spec__ ', ' echo_test1 ', ' echo_test2 ', ' echo_test3 ', ' lixin '] "" "

  

From the output analysis, the role of the SetAttr function is to create a new object, the parameters are the class name of the class to which the new object belongs, the object name of the new object, the value of the object, the value can be a string, or a number, of course, it can also be a function, the above code for simplicity, directly using an anonymous The last delattr is to delete the existing function, the usage rate is low, there is no special attention to the place.

In the process of use, it is also necessary to mention the dynamic acquisition of the class name, such as all the code in the class name, are we fixed input, in practice, this will make the code extremely inflexible. The first parameter of the four reflection functions accepts only the class name and cannot receive the string. The data entered directly by the user is clearly formatted as a string and therefore cannot be used directly. Of course, we can turn strings into class names, but it doesn't have to be that troublesome. Python has the appropriate response, using the following code:

#原代码基础上修改, Interaction classes
__author__ = "Lixin" func_name = input ("What does want to Do?,please enter:") #获取用户输入数据class_name, Func_name = func_name.sp Lit ("/") splits user input data and assigns values to two variable model = __import__ (class_name) #以__import__的形式导入类名, and generates a variable to get the return value flog = hasattr (model,func_ Name) #变量值可以直接当做参数传入, verify here if the function exists if Flog: #如果存在在调用getattr函数, if not present, the data is wrong. func = getattr (model, Func_name) func () Else: print ("Input error") "" "outputs the result as follows:/library/frameworks/ Python.framework/versions/3.5/bin/python3.5/users/penglong/documents/python/s11/day8/echo_example/echo_ Func.pywhat does want to do?,please enter:echo_test/echo_test1# input, class name and function name to/separate echo_test1process finished with exit Code 0 "" "

Above, is the common method of reflection in Python, of course, in the last piece of code, we should verify the existence of the class, but Python does not have a function for this, for example, does not give a defense mechanism, in practice, it is certainly not possible, because the class does not exist, the code can not run, Therefore, it is necessary to give a corresponding error defense mechanism. In addition to finding functions in a class, reflection naturally can also be used to find objects in functions, to look for properties on objects, to own methods, and so on. These actions are based on memory, not on the code itself.

  

Reflection in Python

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.