MCS 275 Spring 2021
Emily Dumas
I added new features to our plane
module between lectures. Let's take a tour of the changes:
Point-Point
gives displacement Vector
Vector
by integer or floatabs(Vector)
gives lengthPoint
and Vector
support equality testing(There are other features we might want in a real-world application, but this will suffice for now.)
It is possible to build a class that is derived from an existing one, so that the new class inherits all the methods and behavior of the existing class, but can add new features, too.
If new class B
is derived from existing class A
in this way, we say:
B
is a subclass of A
(or child of A
or inherits from A
)A
is a superclass of B
(or parent of B
)Some common reasons:
Subclassing should express an "is-a" relationship. Dog and Cat might be subclasses of Pet.
Specify a class name to inherit from in the class definition:
class ClassName(SuperClassName):
"""Docstring of the subclass"""
# ... subclass contents go here ...
There is a built-in class object
that every class inherits from, even if you don't specify it explicitly.
Inheritance patterns are often shown in diagrams. Lines represent inheritance, with the superclass appearing above the subclass (usually).
Let's build a class hierarchy for a simple robot simulation.
Every type of robot will be a subclass of Bot
.
Bot
has a position
(a Point
), boolean attribute alive
, and method update()
to advance one time step.
Subclasses give the robot behavior (e.g. movement).
PatrolBot
walks back and forth.WanderBot
walks about randomly.DestructBot
sits in one place for a while and then self-destructs.We haven't built any of the Bot
subclasses yet, but I have already created:
bots
containing a class Bot
. This robot sits in one place. In bots.py
in the sample code repository.botsimulation.py
to run the simulation and show it with simple text-based graphics.In methods of a subclass, super()
returns a version of self
that behaves like an instance of the superclass.
super()
allows the subclass to call methods of the superclass even if the subclass overrides them.
The from
keyword can be used to import individual symbols from a module into the global scope.
So
import mymodule
# ...
mymodule.useful_function() # module name needed
is equivalent to
from mymodule import useful_function
# ...
useful_function() # no module name needed
Please use from
very sparingly!