The implementation method of calling functions based on strings in python.
In python, functions can be called Based on strings:
1. Use getattr to call a function from a string
In a multi-process, a string may be passed over. How can I call an existing function? The main function is to use the getattr function, this function is used to obtain the object of the function corresponding to this string, and then it can be executed, as shown below:
There are two functions in the module:
[root@python 530]# cat attr.py#!/usr/bin/env pythondef kel(): print 'this is a kel function'def smile(): print 'this is a smile function'if __name__ == '__main__': kel() smile()
In the above attr module, two functions are defined. One function is kel and the other is smile. Then, how can I execute the function based on the string kel and smile, that is, using the getattr function, as follows:
>>> import attr>>> k = getattr(attr,'kel')>>> k()this is a kel function>>> s = getattr(attr,'smile')>>> s()this is a smile function>>> e = getattr(attr,'errors')Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'module' object has no attribute 'errors'
In the first step, directly import the module, the module is an object, and then get the kel () function in attr in getattr Based on the string kel, and finally execute the function, which is implemented here, execute corresponding functions based on different strings.
2. Use a dictionary to call a function
The definition of the above module remains unchanged, but a dictionary can be defined during the call to execute the function according to the dictionary value, as shown below:
>>> import attr>>> d = {'kel':attr.kel,'smile':attr.smile}>>> d['kel']()this is a kel function>>> d['smile']()this is a smile function
Therefore, you can use dictionary values to call functions.
The above two methods are mainly used to call other functions when a string is passed. The first method is to use getattr to execute the function; the second method is to pre-define a dictionary and then execute the dictionary value.
In the above python, the implementation method for calling functions based on strings is all the content that I have shared with you. I hope to give you a reference and support for the help house.