[Python] Invoking multiple functions

Asked 2 years ago, Updated 2 years ago, 21 views

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

2022-09-21 11:50

2 Answers

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


2022-09-21 11:50

You can use eval as follows.

def a(): print('1')
def b(): print('2')

c = ['a', 'b']

eval('a')()
1

eval(c[0])()
1


2022-09-21 11:50

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.