【问题标题】:Python: call a method with the name stored in a variablePython:调用存储在变量中的名称的方法
【发布时间】:2015-01-10 19:07:55
【问题描述】:

我正在编写一个 python 程序,其中包含了另一个 python 文件。

包含的 python 文件有一个我想从调用脚本调用的方法。

喜欢:

#!/usr/bin/python    
include script1

method = sys.argv[1]     # values may be - create or destroy

if method == "create":
    script1.create()
elif method == "destroy":
    script1.destroy()

现在,我想要的是,

#!/usr/bin/python    
include script1

method = sys.argv[1]       # values may be - create or destroy

script1.method()

并且,它应该使用变量method中的value,而不是尝试调用名为method的模块。

【问题讨论】:

  • if method = create ??至少发布有效代码
  • @KarolyHorvath 它只是为了理解应该是伪的......但无论如何,我会纠正它:)

标签: python


【解决方案1】:

您可以使用getattr

method= sys.argv[1]
getattr(script1, method)()

【讨论】:

    【解决方案2】:

    要从script1调用函数,你可以把它变成一个模块。

    script1.py:

    def create():
       pass
    
    def destroy():
       pass
    

    script2.py:

    import script1
    
    script1.create()
    script1.destroy()
    

    【讨论】:

      猜你喜欢
      • 2018-02-08
      • 1970-01-01
      • 2013-12-06
      • 2016-08-27
      • 2015-10-28
      • 2016-07-20
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      相关资源
      最近更新 更多