Search code examples
pythonpython-2.7superclass

Call a method from superclass of superclass


I have a example. I have two classes. A is the superclass of B.

class A(object):
   def p(self):
      print "a"


class B(A):
   def p(self):
      print "b"
      super(A, self).p()

Now i have a new class C. The class C is the child class of B and should overwrite the method p again, like that:

class C(B):
   def p(self):
      print "c"
      # here call the method p of the 'supersuper'class A
      # without calling the method p of the superclass B
   ...

How can i overwrite the method p() of the superclass B in the classC and call the method p() of the supersuperclass A without to call the method p of the superclass B? Has someone a idea?

P/S: The method name must be identical.


Solution

  • Just call A.p(self) directly, this is not what super() was designed to support. Note that you have to pass in self manually as A.p() is an unbound method.

    However, you want to reconsider your class design. Perhaps you want to introduce helper methods; one of these could then be called from A.p() and C.p() but not B.p()? That way B.p() wouldn't have to use super().p() at all, and simply just reuse these helper methods.