["python"]
Call a Python method by name

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")
Use the built-in getattr() function: class Foo: def bar1(self): print(1) def bar2(self): print(2) def call_method(o, name): return getattr(o, name)() f = Foo() call_method(f, "bar1") # prints 1 You can also use setattr() for setting class attributes by names.