Functions are first class objects in Python and so you can dispatch using a dictionary. For example, if foo
and bar
are functions, and dispatcher
is a dictionary like so.
dispatcher = {'foo': foo, 'bar': bar}
Note that the values are foo
and bar
which are the function objects, and NOT foo()
and bar()
.
To call foo
, you can just do dispatcher['foo']()
EDIT: If you want to run multiple functions stored in a list, you can possibly do something like this.
dispatcher = {'foobar': [foo, bar], 'bazcat': [baz, cat]}
def fire_all(func_list):
for f in func_list:
f()
fire_all(dispatcher['foobar'])
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…