Home >Backend Development >Python Tutorial >How to call this function through the string of function name in python
Traverse the functions in the execution list, but the function name obtained from the list is a string, so a type error will be prompted, and the string object cannot be called. What if we want the string to become a callable object? Or do you want to call module attributes and class attributes through variables? There are three ways to achieve this
1. eval()
##eval() is usually used to execute a string expression and return the value of the expression. Here it converts the string into the corresponding function. eval() is powerful but dangerous (eval is evil) and is not recommended.
2, locals() and globals()
locals() and globals() are two built-in functions of python, through which you can access local and global variables in a dictionary.
3. getattr()
getattr() is a built-in function of Python, getattr(object,name) is equivalent to to object.name, but here name can be a variable. Returns the bar method of the foo module Returns the properties of the Foo classThe methodcaller function under the standard library operator
##
The above is the detailed content of How to call this function through the string of function name in python. For more information, please follow other related articles on the PHP Chinese website!