Home >Backend Development >Python Tutorial >Implementation of calling functions based on strings in python
In python, you can call functions based on strings:
1. Use getattr to call functions from strings
In multiple processes, a string may be passed, so how do I call an existing function? The main function is to use the getattr function. This function uses a string to get the function corresponding to the string. The object can then be executed, as shown below:
In the module, there are two functions:
[root@python 530]# cat attr.py #!/usr/bin/env python def 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 function is smile. So how do I execute the function based on the strings kel and smile? That is to use the getattr function, as shown below:
>>> 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 one, import the module directly, then the module is an object, so the kel() function in attr is obtained according to the string kel in getattr, so finally Execution is implemented here, and the corresponding function is executed according to the different strings.
2. Use a dictionary to call the function
The definition of the above module remains unchanged, but when calling, you can define a dictionary, The function is executed based on the value of the dictionary, 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
So the dictionary value can be used to call the function.
The above two methods are mainly used to know how to call other functions when a string is passed. Then the first method is to use getattr to execute the function; the second method is to pre- Just define a dictionary and then execute the dictionary values.
The above implementation method of calling functions based on strings in Python is all the content shared by the editor. I hope it can give you a reference, and I also hope that everyone will support the PHP Chinese website.
For more articles related to the implementation of calling functions based on strings in python, please pay attention to the PHP Chinese website!