by Albert Major
Student inherits from Person, we say “A student is a person.”Student) has all attributes/methods of the superclass (Person) and can add or modify functionality.Defining a subclass:
class LandVehicle(Vehicle):
# This means LandVehicle inherits from Vehicle
pass
Overriding methods:
You can override the superclass’s methods (like __init__ or any other method) in your subclass.
If you override __init__, you can call the original (superclass) __init__ with:
super().__init__(param1, param2, ...)
Adding new methods/attributes:
General Vehicle class
Has a name and a maximum speed.
Demonstrated using __init__, __repr__ (or __str__) for printing.
Example:
class Vehicle:
def __init__(self, name, max_speed):
self.name = name
self.max_speed = max_speed
def __repr__(self):
return f"{self.name}, {self.max_speed}"
Subclass LandVehicle (inherits from Vehicle):
You can store an extra attribute, e.g. the number of wheels.
Overriding the __init__:
class LandVehicle(Vehicle):
def __init__(self, name, max_speed, wheels):
super().__init__(name, max_speed) # call Vehicle's __init__
self.wheels = wheels
# Possibly override __repr__ or add new methods
Subclass WaterVehicle (inherits from Vehicle):
__init__ or adding methods, like def knots(self):.Additional Subclasses
Car(LandVehicle), Bicycle(LandVehicle), Cruiser(WaterVehicle), etc.2 wheels, a car might have 4).super() usage:
When you override a method, you can still call the superclass’s version of that method to avoid duplicating code.
For example:
class Bicycle(LandVehicle):
def __init__(self, name, max_speed):
# We know a bicycle always has 2 wheels, so we fix that:
super().__init__(name, max_speed, wheels=2)
Class-method calls (rarely used in modern Python):
You can directly call a specific superclass’s method by referencing the class name, for example:
Vehicle.__init__(self, name, max_speed)
But this can lead to confusing “spaghetti code.” Generally super() is cleaner.