Pergunta

In the following code how to make the unicode data callable.The error that i get is //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')      
Foi útil?

Solução 2

Create a dict of functions that you want to call using a string:

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

Using class:

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)

Outras dicas

If I understand, what you're trying to do is find the function whose name is referenced by the i.header variable, and then call it. (The title is confusing, it makes the impression you want to make the actual unicode instance callable).

This can be done using the globals():

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

Here is a nice way using a decorator

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

This way it's obvious whether a function is a header handler or not

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top