Call a Python method by name

Solution 1:

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.

Solution 2:

I had similar question, wanted to call instance method by reference. Here are funny things I found:

instance_of_foo=Foo()

method_ref=getattr(Foo, 'bar')
method_ref(instance_of_foo) # instance_of_foo becomes self

instance_method_ref=getattr(instance_of_foo, 'bar')
instance_method_ref() # instance_of_foo already bound into reference

Python is amazing!

Solution 3:

getattr(globals()['Foo'](), 'bar1')()
getattr(globals()['Foo'](), 'bar2')()

No need to instantiate Foo first!