MCS 275 Spring 2024
Emily Dumas
Reminders and announcements:
I polished plane.py
a bit, and may soon add some test code.
You'll look at this more in worksheet 3.
It is possible to do arithmetic with points and vectors.
It is impossible to perform meaningless arithmetic.
(e.g. point+point)
Instead of defining a class from scratch we can have it inherit all the methods and attributes of some other class. Then we can add or change anything we like.
If new class B
inherits from A
in this way, we say:
B
is a subclass of A
(or child of
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.
Vector2 and Point2 might be subclasses of ObjectCartesianCoordinates2.
Specify a class name to inherit from in the class definition:
class ClassName(SuperClassName):
"""Docstring of the subclass"""
# ... subclass contents go here ...
Now, all the methods of the superclass are immediately available as part of self
.
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
active
, and method update()
to advance time.
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 deactivates.We haven't built any of the Bot
subclasses yet, but I have already created:
bots
containing one class Bot
. It 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.Time to start building bots.
Suppose B
inherits from A
.
In a method of B
, calling self.f()
will look for a method B.f
,
and if none is found it will call A.f
.
Usually that's all you need.
But what if B.f
and A.f
both exist, but in a method of B
you really need to call A.f
?
You can, with super().f()
.
Only use it for this special situation.
The from
keyword can be used to import individual symbols from a module into the global
scope.
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!