Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override recursive method in python

When I call the base class recursive method from the derived class, the recursive call is done against the derived method, instead of the base class method. How can I avoid that without modifying base class implementation (in example class A)?

Here is an example

class A(object):
    # recursive method
    def f(self, x):
        print x,
        if x < 0:
            self.f(x+1)
        if x > 0:
            self.f(x-1)
        if x == 0:
           print ""

class B(A):
   # Override method 
   def f(self):
       # do some pretty cool stuff
       super(B, self).f(25)

if __name__ == "__main__":
    A().f(5)
    B().f()

I've got this output:

5 4 3 2 1 0 
25
Traceback (most recent call last):
  File "./test.py", line 19, in <module>
     B().f()
  File "./test.py", line 15, in f
     super(B, self).f(25)
   File "./test.py", line 9, in f
     self.f(x-1)
  TypeError: f() takes exactly 1 argument (2 given)

Thanks in advance,

like image 382
Albert Avatar asked Jul 27 '11 15:07

Albert


1 Answers

Name mangling is the tool for this job. This would look like this in your case:

class A(object):
    # recursive method
    def f(self, x):
        print x,
        if x < 0:
            self.__f(x+1)
        if x > 0:
            self.__f(x-1)
        if x == 0:
           print ""

    __f = f

class B(A):
   # Override method 
   def f(self):
       # do some pretty cool stuff
       super(B, self).f(25)

Explanation from the linked documentation:

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped.

like image 200
Björn Pollex Avatar answered Sep 18 '22 00:09

Björn Pollex