【问题标题】:How to call a method whose name is stored in a variable [duplicate]如何调用名称存储在变量中的方法[重复]
【发布时间】:2013-12-06 22:59:59
【问题描述】:

在以下代码中如何使 unicode 数据可调用。我得到的错误是 //TypeError: 'unicode' object is not callable

 def test(test_config):
    for i in test_config:
      print i.header //prints func1
      print type(i.header) // prints unicode
      try:
        #i.header()//TypeError: 'unicode' object is not callable
        func = globals()[i.header]
        print func  # found it
        func()
      except AttributeError:
        logging.error("Method  %s not implemented"%(i.header)) 

  def func1():
      print "In func1"

 test(u'func1')      

【问题讨论】:

  • 您是否正在尝试调用其 namei.header 变量引用的方法?
  • 请查看更新后的问题
  • 你调用它时希望它做什么?
  • 您希望"print" ('Hello World.') 工作吗?如果是,它在 python 中不会这样工作。

标签: python function-call


【解决方案1】:

如果我理解,您要做的是找到名称被 i.header 变量引用的函数,然后调用它。 (标题令人困惑,它给人的印象是您想让实际的 unicode 实例可调用)。

这可以使用globals()

func = globals()[i.header]
print func  # found it
func()  # call it

【讨论】:

  • 如果想法是i.header 包含一个函数的名称,那么这样的事情是让它工作的最佳方式。但这不是最好的主意 - 将函数名称作为数据传递并不完全安全。如果你能找到不同的设计会更好,比如直接传递函数对象。
  • func = globals()[i.header] KeyError: u'func1'
  • 这意味着名称func1 在您尝试访问它时未定义。你能发布一个完整的例子来说明如何得到这个错误吗?
  • 不,我已经定义了 func1..请查看更新后的问题
  • 很抱歉,您的代码仍然不完整。请发布您的完整示例,包括对test 的调用和错误消息,包括回溯
【解决方案2】:

使用字符串创建要调用的函数的字典:

def test(test_config):
    for i in test_config:
      print i.header //prints func1
      print type(i.header)
      try:
        methods[i.header]()
      except (AttributeError, TypeError):
        logging.error("Method  %s not implemented"%(i.header)) 

def func1():
    print "In func1"
def func2():
    print "In func2"

methods = {u'func1':func1, u'func2':func2} #Methods that you want to call

使用类:

class A:
    def test(self, test_config):
        try:
          getattr(self, i.header)()
        except AttributeError:
           logging.error("Method  %s not implemented"%(i.header)) 

    def func1(self):
        print "In func1"
x = A()
x.test(pass_something_here)

【讨论】:

  • 不使用字典还有其他方法吗?
  • +1 显式字典应该优先于查找 globals()。你不想发现有人不小心有一个名为“test”的标题。
  • @Rajeev 然后使用一个类,然后你可以使用getattr调用方法。
  • 你能给我看看sn-p吗
  • @Rajeev 我添加了一个示例。
【解决方案3】:

这是一个使用装饰器的好方法

header_handlers = {}

def header_handler(f):
    header_handlers[f.__name__] = f
    return f

def main():
    header_name = "func1"
    header_handlers[header_name]()

@header_handler
def func1():
    print "func1"

@header_handler
def func2():
    print "func2"

@header_handler
def func3():
    print "func3"

if __name__ == "__main__":
    main()

这样一来,函数是否是标头处理程序就很明显了

【讨论】:

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