Calling a function from string inside the same module in Python?

后端 未结 2 458
庸人自扰
庸人自扰 2020-12-16 14:11

Lets say I have a function bar inside a module called foo.py . Somewhere inside foo.py, I want to be able to call bar() from the string \"bar\". Ho

2条回答
  •  生来不讨喜
    2020-12-16 14:46

    Use a dictionary that keeps the mapping of functions you want to call:

    if __name__ == '__main__':
      funcnames = {'bar': bar}
      funcnames['bar']()
    

提交回复
热议问题