Bishwa Karki
Bishwa Karki

Reputation: 386

inheritance with recursive method override

class A:
    def m(self, v):
        for i in range(v):
          print("A")
          self.m(v-1)

class B(A):
    def m(self, value):
        print("B")
        super(B, self).m(value)

B().m(3)

Output: B A B A B A

Expected output: BAAAA

On class A, the self object is of B and it's calling method m of class B, but I don't want this to happen.

I know I can change the method name, but that is a constraint, I can not change the name of method.

Upvotes: 1

Views: 71

Answers (2)

Him
Him

Reputation: 5551

You can temporarily overwrite self.m in your instance of B. This makes it so that you don't need to change the definition of A

class A:
    def m(self, v):
        for i in range(v):
          print("A")
          self.m(v-1)

class B(A):
    def m(self, value):
        print("B")
        mB = self.m
        self.m = super(B, self).m
        self.m(value)
        self.m = mB

B().m(3)

Upvotes: 1

Alexander
Alexander

Reputation: 17291

This is certainly a contrived example but you could use a keyword argument that defaults to 0 and a conditional expression that only prints the "B" if the argument is 0, and then increment the argument on subsequent calls.

For example:

class A:
    def m(self, v, count=0):
        for i in range(v):
            print("A")
            self.m(v-1, count=count+1)

class B(A):
    def m(self, value, count=0):
        if count == 0:
            print("B")
        super().m(value, count=count +  1)

B().m(3)

output:

B
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A

Upvotes: 0

Related Questions