tags:

views:

77

answers:

3

If I have an object and a method name in a string, how can I call the method?

class Foo:
    def bar1(self):
        print 1
    def bar2(self):
        print 2

def callMethod(o, name):
    ???

f = Foo()
callMethod(f, "bar1")
+4  A: 

Easy one:

class Foo:
    def bar1(self):
        print 1
    def bar2(self):
        print 2

def callMethod(o, name):
    getattr(o, name)()


f = Foo()
callMethod(f, "bar1")

Take a look at getattr

You can also use setattr for setting Class attributes by names.

Enrico Carlesso
I could not find what to search in the documentation! Thanks!
Jazz
@Jazz, it's under builtins. You might have to do an in-page search with `C-f`
aaronasterling
You're welcome.
Enrico Carlesso
@aaronasterling I know, but I could not find what word to search!
Jazz
A: 
getattr(globals()['Foo'](), 'bar1')()
getattr(globals()['Foo'](), 'bar2')()

No need to instantiate Foo first!

Björn
It was only an example, I have real instance of a real class!
Jazz
Calling a Method of a uninitialized class maybe implies you're doing something wrong.
Enrico Carlesso
what if `foo` isn't in globals?
aaronasterling
A: 
def callmethod(cls, mtd_name):    
    method = getattr(cls, mtd_name)
    method()
mkotechno