How do i call a method by a string name using python?

I have the following class;

class myStringMethod():
    def __init__(self):
        self.func_list= [('func1','print_func1()'),('func2','print_func2()')]

    def print_func1(self, name):
        print name

    def print_func2(self, name):
        print name

    def call_func_by_name(self):
        for func in self.func_list:
            getattr(self, func[1])('Func Name')

if __name__=='__main__':
    strM = myStringMethod()
    strM.call_func_by_name() #Nothing prints out!

No functions get called out, what am i missing?

gath

Answers


your self.func_list should be:

self.func_list= [('func1','print_func1'),('func2','print_func2')]

And the way your code is written it will, of course, print 'Func Name'. I guess you probably meant to pass func[0] there.

Working example:

>>> class myStringMethod():
    def __init__(self):
        self.func_list= [('func1','print_func1'),('func2','print_func2')]

    def print_func1(self, name):
        print(name)

    def print_func2(self, name):
        print(name)

    def call_func_by_name(self):
        for func in self.func_list:
            getattr(self, func[1])('Func Name')

>>> myStringMethod().call_func_by_name()
Func Name
Func Name

maybe offtopic, but maybe your list is actually a dict :

self.functs = {'func1':'print_func1', ...}

and then call with :

for fn in self.functs.values() : self.__dict__[fn]('Func Name')

or even if you wanted to call all 'func_' functions in your class (no func_list here) :

@classmethod
def call_func_by_name(cls)
  for n,f in cls.__dict__.values() : 
     if n.startswith('print_') and hasattr(f,'__call__'): f('Hello')

Need Your Help

Apache Camel : Need advice for Routing

java rest cxf apache-camel

I have a restful webservice build on CXF framework. the requirement is that when someone hits this server i have to fetch some data from content providers like google, bing etc according to the

torch7: Error in fine-tuning a CNN

lua machine-learning torch conv-neural-network

I am trying to fine-tune a pre-trained OverFeat conv-net (CNN) on a dataset of images of multi-class faces. My training-testing lua script is based on the tutorial given here.