Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call methods by string

I have the following class.

func_list= ["function1", "function2", "function3"]

class doit(object):
    def __init__(self):
        for item in func_list:
            if item == "function1":
                self.function1()
            elif item == "function2":
                self.function2()
            elif item == "function3":
                self.function3()

    def function1(self):
        #do this
        pass
    def function2(self):
        #do that
        pass
    def function3(self):
        pass

If an instance of this class is created, it iterates over a list of strings and calls methods depending on the actual string. The strings in the list have the names of the corresponding methods.

How can I do this in a more elegant way? I don't want to add another elif-path for every "function" I add to the list.

like image 620
wewa Avatar asked Jul 25 '12 12:07

wewa


1 Answers

func_list= ["function1", "function2", "function3"]

class doit(object):
    def __init__(self):
        for item in func_list:
            getattr(self, item)()
    def function1(self):
        print "f1"
    def function2(self):
        print "f2"
    def function3(self):
        print "f3"



>>> doit()
f1
f2
f3

For also private functions:

for item in func_list:
     if item.startswith('__'):
         getattr(self, '_' + self.__class__.__name__+ item)()
     else:
         getattr(self, item)()

.

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

http://docs.python.org/library/functions.html#getattr

like image 196
applicative_functor Avatar answered Oct 10 '22 02:10

applicative_functor