如何调用名称存储在变量中的方法

时间:2013-11-22 06:31:19

标签: python function-call

在下面的代码中,如何使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')      

3 个答案:

答案 0 :(得分:3)

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

这可以使用globals()

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

答案 1 :(得分:3)

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

def test(test_config):
    for i in test_config:
      print i.header //prints func1
      print type(i.header)
      try:
        methods[i.header]()
      except (AtributeError, 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:

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

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

答案 2 :(得分:2)

这是使用装饰器的好方法

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()

这样很明显函数是否是标题处理程序

相关问题