[Tutor] __init__() - is it required?

Alan Gauld alan.gauld at btinternet.com
Sun Jan 9 22:42:39 CET 2011


"Corey Richardson" <kb1pkl at aim.com> wrote

> Do all classes need an __init__() method? I have classes that look 
> much
> like this one starts out:

No, init() is only for initialising the object instance.
If you have no local instance spwecific initialisation
you can leave it to the inherited init() aor have no init()
at all.

OTOH If you do have no need for an init it implies you
probably have no instance variables, which is somewhat unusual.
Not unheard of - you may only be modifying the behaviour of an
inherited class - but it is unusual.

> class GenerateXML(object):
>    """Defines methods to be inherited for StaticXML and 
> AnimationXML"""
>    def __init__(self):
>        pass


IN this case it is a waste of time. It could even do harm in cases
where you ingherit from a superclass that does have an init()
since the pass will mean it never gets called! Whereas if you
omit the init() the suiperclass init(if it exists) will get called.

HTH,


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




More information about the Tutor mailing list