[Tutor] Trouble understanding modifying parent class..
alan.gauld at btinternet.com
Tue Apr 14 10:16:54 CEST 2009
"Eric Dorsey" <dorseye at gmail.com> wrote
> 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
> Do we have to call the __init__ of the parent somehow? Is it "replaced"
> overridden in an __init__ method of the subclass?
You replace the behaviour you want to change, but in the replaced
version you may choose to call the parent version.
This typically leads to very simple methods in the subclass, as in your
def __init__(self, name, value=2):
This defines a new init method which has a new default value.
It then calls the original parent init method passing the name
and value so that the A default never gets used in B instances.
The OOP topic in my tutor describes this in more detail.
Author of the Learn to Program web site
More information about the Tutor