【问题标题】:call defining by variable in python在python中调用由变量定义
【发布时间】:2015-04-21 05:45:52
【问题描述】:

我有两个文件

test_def.py
def hi_test(a):
    return a

test_run.py

from test_def import hi_test
a = 'hi'
b = 'test'
c = 'lion'

run = "{0}_{1}".format(a, b)
run1 = run(c)
print run1

它正在打印 hi_test(lion) 而不是执行/调用 def 函数。 任何人都可以帮助执行 def 功能吗?

【问题讨论】:

标签: python function


【解决方案1】:
import test_def
a = 'hi'
b = 'test'
c = 'lion'

run = "{0}_{1}".format(a, b)
run1 = getattr(test_def, run)(c)
print run1

【讨论】:

    【解决方案2】:

    可以通过以下方法存档。

    import test_def
    a = 'hi'
    b = 'test'
    c = 'lion'
    
    run = "{0}_{1}".format(a, b)
    run1 = getattr(test_def,run)
    run2 = run1(c)
    print run2
    

    【讨论】:

      【解决方案3】:

      test_def.py

      def hi_test(a):
          print a
      

      test_run.py

      from test_def import hi_test
      
      a = 'hi'
      b = 'test'
      c = 'lion'
      
      run = "{0}_{1}".format(a, b)
      exec("%s('%s')"%(run, c))
      

      虽然,第一个答案更好

      【讨论】:

        猜你喜欢
        • 2023-03-10
        • 2017-09-21
        • 1970-01-01
        • 2018-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多