0

I wanted to know which class method is being executed in example below. Is there a way to call explicitly using class name? Kindly help.

Example:-

class A():

    def test(self, input):
        print(input)


class B(A):
    def test(self, input):
        print(input)


class C(B):

    def testing(self):
        super().test("foo")
        super().test("boo")

run = C()
run.testing()

Output:-

foo
boo

In order to experiment, I tried calling via class name but received error. I understand that, self is for class objects and therefore, should be called via either super() or reference object but my question is how will I know which method is being called during execution and are there any other way to directly call parent method (From Class A) explicitly from Class C?

class A():

    def test(self, input):
        print(input)


class B(A):
    def test(self, input):
        print(input)


class C(B):

    def testing(self):
        A.test("foo")
        B.test("boo")

run = C()
run.testing()

Output:-

 A.test("foo")
TypeError: test() missing 1 required positional argument: 'input'
3
  • 4
    A.test(self, "foo") etc. Also don't name your parameters input, it overrides the input function! Commented May 18, 2021 at 17:14
  • It worked! Thanks! Commented May 18, 2021 at 17:16
  • 1
    "but my question is how will I know which method is being called during execution" super will call the next method in the method resolution order Commented May 18, 2021 at 17:27

1 Answer 1

1

Additional information about the answer that @Samwise gave to your error message:

Methods are actual functions that has an object bound to them. When you call a function on an instance of a class, python will fill the first parameter of your function for you with the reference to that instance and then it become "method". But if you call a function on a class itself, python won't fill the first parameter for you so you have to do it yourself. (This is the reason you got: missing 1 required positional argument: 'input' )

class A:
    def foo(self):
        pass

print(type(A.foo))
print(type(A().foo))

As you can see the first one is "function" , second one is "method". In the first one, you should fill input (what a bad name) manually.

This is the behavior of descriptors. "Functions" implement descriptor protocols.

Sign up to request clarification or add additional context in comments.

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.