Lesson explanation
After this lesson, you will be able to:
super() when an override should extend, rather than replace, parent behavior.Inheritance creates a relationship between types. Polymorphism lets code work with different objects through a shared method name. A subclass overrides a method by defining a method with the same name. Calling obj.summary() uses the implementation belonging to that object.
This is the Python counterpart of overriding methods in Java or C#, but you do not have to add @Override to make it work. Keep the same expected parameters and return behavior so callers do not have to know the concrete subclass.
Use super().method() when the parent already does useful work that you want to preserve. A loop can then process different objects through the same interface, instead of checking their types and duplicating branches.
A subclass returns a specialized label when the same method is called.
class Device:
def status(self):
return "unknown"
class Router(Device):
def status(self):
return "online"
print(Device().status())
print(Router().status())Output:
unknown
onlineThe loop doesn't need to know the exact subclass of each item.
class Alert:
def level(self):
return "general"
class WarningAlert(Alert):
def level(self):
return "warning"
class ErrorAlert(Alert):
def level(self):
return "error"
alerts = [WarningAlert(), ErrorAlert(), Alert()]
for alert in alerts:
print(alert.level())Output:
warning
error
generalsuper() reuses the base message before adding subclass information.
class Build:
def summary(self):
return "Build complete"
class VerifiedBuild(Build):
def summary(self):
return f"{super().summary()} | tests passed"
print(VerifiedBuild().summary())Output:
Build complete | tests passedEach class supplies a label() method, so the caller can handle them uniformly.
class Transport:
def label(self):
return "standard"
class ExpressTransport(Transport):
def label(self):
return "express"
def describe(transport):
return f"Shipping: {transport.label()}"
print(describe(ExpressTransport()))Output:
Shipping: express| Concept | Key idea |
|---|---|
| Method override | Subclass defines the same method name |
| Polymorphism | Call the same method on different object types |
super().method() | Reuse the parent implementation |
| Shared interface | Caller does not need to branch on each subclass type |