Home > Enterprise >  python: call a parent class' recursive function
python: call a parent class' recursive function

Time:03-15

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)
        a_helper(i) 

    def a_helper(self, i):
        if i <= 0:
            return
        print("A", i)
        self.a_helper(i - 1) 

CodePudding user response:

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