On Tue, Apr 14, 2009 at 11:27 AM, Eric Dorsey <dors...@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 cheers, Guillaume _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor