Home > Net >  inheritance with recursive method override
inheritance with recursive method override

Time:10-30

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.

CodePudding user response:

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)

CodePudding user response:

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