0

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?

1
  • 1
    foo(foo.bar_1)? Commented Jan 23, 2023 at 6:08

3 Answers 3

1

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

foo = FOO()
foo(foo.bar_1)
Sign up to request clarification or add additional context in comments.

1 Comment

I think the naming isn't right here. Its not a class method, Those are created with the @classmethod decorator. You make use of an instance method.
1

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>>

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.