【问题标题】:Dynamic Function Calling From a Different File - Python从不同的文件调用动态函数 - Python
【发布时间】:2021-04-22 07:26:49
【问题描述】:

我有 2 个 python 文件。一个文件具有所有功能,另一个文件具有从第一个文件调用函数的功能。这是我所拥有的简化版本。

file1.py

def one():
        print("Hello World")
def two():
        print("Salutations Earth")
def three():
        print("Greetings World")

file2.py

import file1
function_id = input("Which function would you like? Please enter(one, two or three): ")
file1.function_id()

显然,这是行不通的,因为 file1 中没有名为“function_id”的函数。但是,我不确定如何从 file1 动态调用函数。我看了youtube,其中一个视频建议使用 eval() 但它对我不起作用。感谢您的宝贵时间!

【问题讨论】:

    标签: python python-3.x function dynamic


    【解决方案1】:

    在file1.py中,像这样添加一个函数字典:

    function_dict = {'one':one, 'two':two, 'three':three}
    

    然后在 file2.py 中,将 file1.function_id() 替换为:

    file1.function_dict[function_id]()
    

    【讨论】:

      【解决方案2】:

      在模块file1上使用getattr()

      import file1
      
      function_name = input("Which function would you like? Please enter(one, two or three): ")
      function = getattr(file1, function_name, None)
      
      if function:
          function()
      else:
          print(f"No such function: {function}")
      

      注意:执行任意用户输入是不安全的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-23
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 2018-07-27
        • 1970-01-01
        相关资源
        最近更新 更多