On Mon, Aug 29, 2016 at 09:18:17PM +0000, monik...@netzero.net wrote:
> Hi:
> Why in super(Child,self).setVal(value) there is Child and self in super? Why 
> the repetition? Or should it say Parent instead of Child?
> In my understanding it should say Parent2 instead of Child since it refers to 
> which parent to take the medthod from. In case of multiple inheritance it 
> should state the class from which super will take the setVal method.
> Please explain what Im missing here.

A lot :-)


No, super() doesn't specify which parent to take the message from, 
because in multiple inheritence you normally need to take it from ALL 
parents:

class Child(Parent1, Parent2):
    def setVal(self, value):
        Parent1.setVal(self, value)
        Parent2.setVal(self, value)

If you're writing that, then super() is a better solution.

def Child(Parent1, Parent2):
    def setVal(self, value):
        # This will automatically call both Parents
        super(Child, self).setVal(val)


It is better because in complex class hierarchies that form a diamond 
shape, calling each parent by hand may cause one of the methods to be 
called twice. super() will avoid that.

What if the method is only defined once? Let's say that Parent1 defines 
setVal, but Parent2 doesn't. Or worse, you're not sure whether they both 
have a setVal method -- at least one does, for sure, but maybe both of 
them do, and you're not sure which.

super() to the rescue. If you always use super(), it will ensure that 
the method is called from each parent that has it, but not from parents 
that don't. (So long as at least one parent has the method.)

It might help to see what Raymond Hettinger has said about super:

https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

Or if you prefer a video:

https://www.youtube.com/watch?v=EiOglTERPEo


And remember, in Python 3 (but not Python 2) you can just call super() 
with no arguments, and the interpreter will work out what you mean.



-- 
Steve
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
  • [Tutor] super monik...@netzero.net
    • Re: [Tutor] super Steven D'Aprano

Reply via email to