20.2. Introduction to Inheritance - Point and LabeledPoint¶
Recall the Point class from earlier in the book:
Now, suppose we want to create a class that works like Point
in every respect, but also keeps track of a short description for the point.
We could create a LabeledPoint
class by copying and pasting the definition for
Point
,
changing the name to LabeledPoint
, and modifying the class to suit our
purposes. However, any time you copy and paste code, keep in mind that
you are copying and pasting bugs that may exist in the code. Inheritance
provides a way to reuse the definition of Point without having to copy and
paste.
We begin like this:
This example defines a class named LabeledPoint
that inherits from the Point
class.
Putting the name Point
in parenthesis tells Python that the new class,
LabeledPoint
, begins with all of the methods defined in its parent, Point
.
For example, we can instantiate LabeledPoint using the Point constructor, and
invoke any Point methods we want to on it:
p = LabeledPoint(7,6)
dist = p.distanceFromOrigin()
- def class Student(Person):
- You do not use the def keyword to define a class
- def class Student extends Person:
- You do not use the def keyword to create a class and use (Parent) to inherit
- class Student(Person):
- Correct!
- class Student extends Person:
- Use (Parent) to inherit from a Parent class
Q-3: Which of the following correctly declares a Student class that inherits from a Person class?
Now, let’s refine LabeledPoint so that it holds a label, along with the x and y coordinates:
Here, we have redefined two of the methods that LabeledPoint inherits from Point:
__init__()
and __str__()
.
This is called overriding. When a child class redefines methods that are defined
in its parent, we say that the child overrides the functionality inherited from
its parent. When both the parent class and child class have a method with the
same name, an invocation of the method on an instance of the child class
executes code in the child’s class; an invocation of the method on an instance
of the parent class executes code in the parent’s class. For example,
consider the following:
In Line 4, the call to str(pt)
invokes the __str__()
method in Point
, because
pt refers to an instance of Point
. In Line 5, the call to str(labeledPt)
invokes the __str__()
method in LabeledPoint
, because labeledPt
refers to an instance of LabeledPoint
.
-
Q-6: Drag each item to its definition
Read the chapter on functions and try again.
- child
- A class that inherits from another class
- parent
- The class being inherited from
- override
- Defining a method with the same name as a parent method. This method will be called instead of the parent method.
- inheritance
- A way to reuse code from another class without having to copy and paste code