MCS 275 Spring 2023
Emily Dumas
Reminders and announcements:
I added new features to our plane module between lectures.
These are explored a bit in Worksheet 3. Included:
Vector2 by integer or floatabs(Vector2) gives length
Photo by Mike Gogulski (CC-BY-SA)
Instead of starting a class definition from scratch we can indicate that it should inherit all the methods and attributes of some other class. Then we only need to specify the changes.
If new class B inherits from existing class 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.
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 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 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.If you define a method in a subclass, it replaces any method of the same name in the superclass.
That's usually very helpful. But what if the replacement wants to call the method it is replacing?
super().method_name(...) is the syntax for this; it calls method_name(...)
of the superclass even if that method is redefined in the subclass.
You only need super() under specific circumstances:
This is rare. More common: Needing to call a method of the superclass that isn't redefined in the subclass.
That's easier: Just use self.method_name(...).
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!