Calling a Function Dynamically Using a String
Calling a function using a string that contains the function's name can be useful in certain scenarios. Here's how you can achieve this:
Utilizing getattr()
The getattr() function allows you to retrieve attributes dynamically. To call a function using a string, you can use the following approach:
import foo func_name = "bar" bar = getattr(foo, func_name) result = bar()
In this example, we import the foo module, and then we use func_name to retrieve the reference to the bar function using getattr(). Finally, we can call the function and store the result in result.
Understanding getattr()
getattr() takes two arguments:
getattr() can be used to access not only functions but also class instance bound methods, module-level methods, and even class methods.
The above is the detailed content of How Can I Dynamically Call a Function in Python Using a String?. For more information, please follow other related articles on the PHP Chinese website!