1

I cannot quite understand the following result:

class A:
    def a(self, i):
        if i <= 0:
            return
        print("A", i)
        self.a(i - 1)  # line 6


class B(A):
    def a(self, i):
        print("B", i)
        super().a(i)   # line 12


if __name__ == '__main__':
    b = B()
    b.a(3)

result is:

B 3
A 3
B 2
A 2
B 1
A 1
B 0

In line 12, it calls the parent class A's function, however when a() recursively call itself, it uses the B's version. Why it happens?

How can I get the following result (I still want to override parent's function a()):

B 3
A 3
A 2
A 1

I want to force the instance only uses function in parent's version.

I have this requirement since I meet similar problem in some practical problem. I still have to name the function as a in class B. However most part of logic is duplicate in A and I want to reuse it.

Right now I can only use the following way to implement B:

class B(A):
    def a(self, i):
        print("B", i)
        self.a_helper(i) 

    def a_helper(self, i):
        if i <= 0:
            return
        print("A", i)
        self.a_helper(i - 1) 
7
  • 2
    Methods are looked up based on the class of the object, not the class where the method is defined. Since self is a B instance, self.a() calls the B method. Commented Mar 8, 2022 at 20:19
  • @Barmar Thank you. Then how to handle the second question? Commented Mar 8, 2022 at 20:21
  • 1
    Don't override method a in class B. Perhaps call the method a different name. Commented Mar 8, 2022 at 20:23
  • 1
    You can call methods directly: A.a(self, i) Commented Mar 8, 2022 at 20:25
  • 1
    But this negates some of the benefits of OOP. Subclasses are supposed to be able to override the parent methods. Commented Mar 8, 2022 at 20:27

1 Answer 1

1

Call the method directly as an ordinary function, rather than going through the instance.

class A:
    def a(self, i):
        if i <= 0:
            return
        print("A", i)
        A.a(self, i - 1)  # line 6
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.