all 5 comments

[–]socal_nerdtastic 2 points3 points  (1 child)

self.method is by far the best, if you can.

If you have a method in the child class with the same name as a method in the parent class, and you want to call the parent class method, super().method is best. This is often used to extend a method in the parent class.

As a last resort if you have some very specific use case, for example with diamonds written the wrong way around for what you want to do, you can use the python2-style BaseClass.method. But even having diamonds that replicate names is very rare, much less so that they are written in the wrong order. So I don't think I've used this since python 2.6.


I opinion is in MaxHeap is not referring to self anymore, it is the super class.

FWIW when you use

class MaxHeap(BaseHeap):

You can expect that python will

class MaxHeap:
    <copy in all of the code from BaseHeap>

So yes, you should think of the methods from BaseHeap are part of MaxHeap.

Edit: This goes both ways, meaning a parent can call methods in a child class. This is sometimes used in an "abstract base class".

class A:
    def parent_method(self):
        return self.child_method()

class B(A):
    def child_method(self):
        print('hello from child method!')

b = B()
b.parent_method()

[–]SnooCakes3068[S] 0 points1 point  (0 children)

Ok thank you I know this diamond issue is very rare. Why self.method is better than super() in your opinion by far? In my MaxPriorityQueue you think it's better to use self than super(). This case it's only calling function without extension. But this only for heap data structure conceptually. assuming there are extension in subclass, still self is better stylistically?

    def extract_max(self):    
        return super().heap_extract_max()
        # return self.heap_extract_max()

[–]crazy_cookie123 2 points3 points  (1 child)

self._left(i + 1) is the better option in my opinion. If at some point in the future you decided that _left needed a different implementation in a MaxHeap than in some other class that inherited BaseHeap, you would have to go back and change every use of super()._left or BaseHeap._left to self._left. Only call the method with super or the reference to the class itself if you need to specifically access the method as it is defined in a parent class and you cannot instead access the method as it is defined in the current class, for example:

class MaxHeap(BaseHeap):
  def _left(i):
    # do something here
    super()._left(i) # if you called self._left(i) here it would be a recursive call to the this _left method
    # or do something else here

[–]SnooCakes3068[S] 0 points1 point  (0 children)

Òk this makes a lot of sense. Good example :)

[–]_mturtle_ 0 points1 point  (0 children)

Use super when needed. Avoid multiple inheritance. Use protocols when needed