Call a Python method by name

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.

Leave a Comment