Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python second level inheritance

I'm kinda new to python, but I've got a question about second level inheritance.

I have this situation:

class A:
  def Something(self):
     #Do Stuff

class B(A):
  def SomethingElse(self):
     #Do other stuff

class C(B):
  def Something(self):
     #Do additional stuff

Note that class C inherits from B which inherits from A, but that class B DOES NOT implement method Something().

If I call super(C, self).Something() for an instance of class C, what will happen? Will it call the method from class A?

Additionally, if class B does implement Something(), but I want to call class A's Something() directly from class C (ie bypass class B's implementation), how do I do it?

Finally, can someone explain to me why people user super() rather than just calling the parent class's methods directly? Thanks.

like image 258
Migwell Avatar asked Jun 24 '13 12:06

Migwell


2 Answers

In the first case, where B does not implement Something, calling super will fall up to the place where it is defined, ie A.

In the second case, you can bypass B by calling A.Something(self).

The main reason for using super is for those cases where you have multiple inheritance: Python will always call the next definition in the MRO (method resolution order).

See Raymond Hettinger's excellent article Super considered super!.

like image 187
Daniel Roseman Avatar answered Nov 10 '22 07:11

Daniel Roseman


  1. Yes, it will call Something() from the A class.
  2. You can always call A.Something(self) from C.

Explanation for super() and other calling conventions would take a while. Have a look at the original article about MRO and Python's Super is nifty, but you can't use it.

like image 5
viraptor Avatar answered Nov 10 '22 09:11

viraptor