gath
gath

Reputation: 25492

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

Upvotes: 0

Views: 243

Answers (2)

makapuf
makapuf

Reputation: 1410

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

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319889

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

Upvotes: 3

Related Questions