Home > front end >  How to call class function by parameter in python
How to call class function by parameter in python

Time:01-23

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?

CodePudding user response:

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

foo = FOO()
foo(foo.bar_1)

CodePudding user response:

Yes. A instance method keeps a reference to its object. So you can do

foo(foo.bar_1)

To see the difference, bar_1 is a function on the class but becomes a method on the instance

>>> FOO.bar_1
<function FOO.bar_1 at 0x7f0da7583d90>
>>> foo.bar_1
<bound method FOO.bar_1 of <__main__.FOO object at 0x7f0da756a080>>

CodePudding user response:

To access bar_1 by parameter, Please call it using the object foo.

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(foo.bar_1)

Output: inside bar 1

  • Related