def a(): print('1')
def b(): print('2')
Assume that there are two functions, a and b above.
If the variable is stored in the list c = ['a', 'b'] str, is there a way to call both functions a and b in the for statement?
Or is there another way to call both functions?
python
Python is also a function object. So you can put a function in a variable, and you can use it as it is.
def a(): print('1')
def b(): print('2')
c = [a, b]
for cb in c:
cb()
Answer to a question correction.
If you only have the name of the function, not the object of the function, you can call it in two ways.
Use the globals
built-in function. Gets the global symbol table for the current module into a dictionary.
def a(): print('1')
def b(): print('2')
c = ['a', 'b']
for cb_name in c:
globals()[cb_name]()
Use getattr
.
# utils.py
def a(): print('1')
def b(): print('2')
import utils
c = ['a', 'b']
for cb_name in c:
getattr(utils, cb_name)()
You can use eval as follows.
def a(): print('1')
def b(): print('2')
c = ['a', 'b']
eval('a')()
1
eval(c[0])()
1
© 2025 OneMinuteCode. All rights reserved.