Search code examples
pythonclassparametersarguments

How to call class function by parameter in python


Below is a sample code

def bar_2():
    print("inside bar 2")

class FOO:
    def __call__(self, *args):
        for arg in args:
            arg()
    def bar_1(self):
        print("inside bar 1")


foo = FOO()
foo(bar_2)

Output: inside bar 2

But if I want to call foo(bar_1)

Output: NameError: name 'bar_1' is not defined. Did you mean: 'bar_2'?

Is it possible to call bar_1 by parameter?


Solution

  • class methods can only be referenced with class object. So it can be like:

    foo = FOO()
    foo(foo.bar_1)