[Tutor] access class through indexing?

Alan Gauld alan.gauld at btinternet.com
Thu Aug 5 12:40:15 CEST 2010


"Alex Hall" <mehgcap at gmail.com> wrote

>> Since you never call super(), the init of the base class never 
>> happens.
...
>> actual object you're supposed to be initializing, and you 
>> immediately
>> overwrite it (self) with another object.  As a result, everything 
>> else
>> you do in that method is thrown out when the method returns.

> That makes sense, and doing so has fixed everything. I am still not
> clear on the whole super() thing; I saw it in another project and
> tried to find out about it, but what I found was very confusing, and
> super() did not seem terribly important, so I did not pursue the
> matter further. Apparently it is important...

It is critical.
Methods are not simply functions that happen to be defined in a
class structure. They are intended to be part of a complete 
heirarchical
calling mechanism. It is normal when writing a method of a derived
class that over-rides an inherited method to call the inherited method
somehwhere in the body of your method.

class C(A):
     def myAmethod(self)
           #  put local initialisation code here
           #  call the superclass version of the method here
           #  call local tidy-up code here

The initialisation and tidy-up code is what is unique to your version
of the class (and are optional but if neither exists you don't need
to override the method!). But to get the inherited functionality
(including init*() ) to work you must call the inherited method.
If you don't you replace the inherited functionality and talke full
responsibility for doing everything that it used to do yourself.

Using super() is the approved way of doing it, but for single 
inheritance
you can call the parent class directly

A.myAmethod(self)

if you find that less mind bending.
But calling the superclass version of your method is vital if you want
to get the benefits of inheritance.

Finally, if you did want to replace what self was you can do that
by writing your own __new__ method rather than an __init__ but
you very rarely want to do that!

Python gives you a lot of tools to mess with how objects work.
Unless you really know what you are doing it's usually best to
ignore the temptation! :-)

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list