--- reflected in python with the calling function and method of strings

We will encounter such a scene in practical applications: after a written code, we hope to enter the code instructions directly call a function or method, the usual practice, we will use an if statement to achieve,

a=input('<<<')
if a == 要输入的指令
代码块
elif a==要输入的指令
代码块
....

When it is judged less time required, this is no problem, but requires more time determination code, the code will become very long.

Then we can use reflection to quickly achieve this functionality.

Reflection: data type is a string, to the manipulated variable, method, function and the like.

Commonly used reflective methods are:

getattr () method to get reflected

the hasattr () method determines whether there is reflected, generally used with getattr

1) is reflected in the class. Can be obtained by object name of the object properties and methods, you can also get a static property, class methods, and static methods with the class name. Code format is as follows:

getattr (or object class name, "property name")

class A:
    def __init__(self,name):
        self.name=name
    def func(self):
        print('test')
a=A('apple')
print(a.name)
print(getattr(a,'name'))

The above code example, rows 7 and 8 may be implemented requirements, but by getattr () method, we can achieve with a human-computer interaction INPUT (), such as this into the following codes:

class A:
    def __init__(self,name):
        self.name=name
    def func(self):
        print('test')
a=A('apple')
b=input('<<<')
print(getattr(a,b))

We can, human-computer interaction by entering a property to view

If the class method to be invoked, can use the following code, c after reflection generated memory address, so it needs to call back parentheses

c=getattr(a,'func') 
c()

---------------------------------------Dividing line--------- ---------------------------

Reflected in the module, the principle is the same code format as follows:

getattr (module name, "function")

For example, we can test the following code in the time module:

import time
a=getattr(time,'localtime')
c=time.strftime('%Y-%m-%d',a())
print(c)

The above code is equivalent to

import time
c=time.strftime('%Y-%m-%d',time.localtime())
print(c)

The code length look the same, but the former can be achieved in the human-machine interaction, without the need for complex decision

---------------------------------------Dividing line--------- ---------------------------

Although the above code to meet the requirements, but there is a risk, once the input string can not be found, it will error, so we need to use another method to be used in conjunction, is hasattr (), its role is to determine the presence of a master string, can be invoked, under the code if we will modify the second line does not change the way

import time
a=getattr(time,'localtime1')
c=time.strftime('%Y-%m-%d',a())
print(c)

The following error occurs
Here Insert Picture Description
then we can use hasattr judge can also design errors prompt, as follows:

import time
if hasattr(time,'localtime1'):
    a=getattr(time,'localtime1')
    c=time.strftime('%Y-%m-%d',a())
    print(c)
else:
    print('代码错误')

The results are as follows:
Here Insert Picture Description
summarized as follows:

1) when we need some interactive or interactive data, such as input using input string read from a file, or to implement a method call some functions may be implemented using the reflection method.

2) reflection method can be achieved, judging by the if statement can also be achieved, but more needs reflection method is more simple

3) Because the internal reflection is called and executed the code, so security will be higher!

Published 13 original articles · won praise 1 · views 190

Guess you like

Origin blog.csdn.net/aa12551827/article/details/104916397