Home >Backend Development >Python Tutorial >How Can I Call a Python Function Dynamically Using Its Name?
In Python, there are instances where you may require calling a function using its name stored as a string. This approach offers flexibility and can be useful in various scenarios.
To dynamically invoke a function using its string representation, you can employ the getattr() function. Consider the following example:
import foo func_name = "bar" bar = getattr(foo, func_name) result = bar() # executes foo.bar()
In this example, we have a module named foo with a function named bar. We store the function's name as a string (func_name) and utilize getattr() to retrieve a reference to the function object. The result variable now contains the return value of the foo.bar() function call.
It's important to note that getattr() is versatile and can be applied to instance-bound methods, module-level functions, class methods, and more. Its dynamic nature allows for flexible access to methods and functions regardless of their invocation context.
The above is the detailed content of How Can I Call a Python Function Dynamically Using Its Name?. For more information, please follow other related articles on the PHP Chinese website!