How to call this function through the string of function name in python

silencement
Release: 2019-05-25 16:21:51
Original
5757 people have browsed it

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()

How to call this function through the string of function name in python

##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()

How to call this function through the string of function name in python

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

How to call this function through the string of function name in python

Returns the properties of the Foo class

How to call this function through the string of function name in python

The methodcaller function under the standard library operator

How to call this function through the string of function name in python

##

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template