Using user input to call functions

前端 未结 4 1097
眼角桃花
眼角桃花 2020-12-06 15:11

I was trying to make a \"game\" in Python where the user inputs a command. However, I do not know whether you can take that input to be a function name. This is my current e

4条回答
  •  独厮守ぢ
    2020-12-06 16:07

    You can access functions by name using:

    function = globals()[function_name]
    

    if the function is in the current module, or

    function = getattr(other_module, function_name)
    

    You should also take measures to disallow calling arbitrary functions, for example, prefixing:

     def cmd_move() # ok to call this
     def cmd_jump() # ok to call this
    
     def internal_func....
    
     cmd = raw_input('>') # e.g. "move"
     fun = globals()['cmd_' + cmd]
     fun()
    

提交回复
热议问题