[Tutor] Trouble understanding modifying parent class..

Guillaume Chereau charlie137 at gmail.com
Tue Apr 14 06:31:58 CEST 2009

On Tue, Apr 14, 2009 at 11:27 AM, Eric Dorsey <dorseye at gmail.com> wrote:
> Hi tutors, I am studying classes a bit, and am having trouble with this
> concept and would appreciate your help!
> class A:
>     def __init__(self, name, value=1):
>         self.name = name
>         self.value = value
> And now I want a subclass, one that overrides the value=1 and defaults to
> value=2, how do I code that? I'm understanding subclasses that have
> different methods that have different behavior, but I'm having trouble doing
> this.
> Do we have to call the __init__ of the parent somehow? Is it "replaced" or
> overridden in an __init__ method of the subclass?
> .. or stated simply:
> If you have class A: which has def __init__(self, name, value=1), how do you
> code a subclass B(A): that automatically starts with value=2?

Simply type :

class B(A):
    def __init__(self, name, value=2):
        super(B, self).__init__(name, value)
        # rest of the __init__ method

"super" will automatically call the __init__ method of the parent class (A)
You can also do like this, but it less clean :

class B(A):
    def __init__(self, name, value=2):
        A.__init__(self, name, value)
        # rest of the __init__ method


More information about the Tutor mailing list