19.3. Extending¶
If you compare the code in the __init__ methods of Point
and LabeledPoint
, you can
see that there is some duplication–the initialization of x and y. We can
eliminate the duplication by having LabeledPoint
’s __init__()
method invoke
Point
’s __init__()
method. That way, each class will be responsible for
initializing its own instance variables.
A method in a child class that overrides a method in the parent can invoke
the overridden method using super()
, like this:
1 class LabeledPoint(Point):
2
3 def __init__(self, initX, initY, label):
4 super().__init__(initX, initY)
5 self.label = label
In this example, line 4 invokes the __init__()
method in Point
,
passing the values of initX
and initY
to be used in initializing the x
and y
instance variables.
Here is a complete code listing showing both classes, with a version
of __str__()
for LabeledPoint
that invokes its parent’s implementation
using super()
to avoid duplicating the functionality provided in Point
.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.