Extend behavior with inheritance and composition
Reuse an interface with a subclass and assemble objects with composition.
Jump to the automation labA subclass inherits methods from its base class. Override a method to specialize the behavior and call super() to extend behavior from the parent. A caller can use the same method on multiple related kinds of objects.
Use composition when one object holds another object as a collaborator. For example, a delivery report can hold a shipment and ask it for the fee. The report need only know the method the shipment provides.
Exception classes follow the same inheritance model. A custom InvalidBookingError(ValueError) is caught by an except ValueError handler. BaseException also covers signals such as KeyboardInterrupt, so catch the specific type you know how to handle.
The standard fee is twice the weight.
Run the example and practice
Override ExpressShipment.fee() to add a flat fee of 4 to the standard fee. Keep the receipt compatible with either shipment.
Target output
Fee: 6
Fee: 10Show a hint
Return super().fee() + 4 in the subclass.
Ready
Run your code to see the output here.
Check output also tests your code with additional cases.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
class Shipment:
def __init__(self, weight):
self.weight = weight
def fee(self):
return self.weight * 2
class ExpressShipment(Shipment):
def fee(self):
return super().fee() + 4
class Receipt:
def __init__(self, shipment):
self.shipment = shipment
def label(self):
return f"Fee: {self.shipment.fee()}"
for shipment in [Shipment(3), ExpressShipment(3)]:
print(Receipt(shipment).label())Automation lab
Preview reminders for different channels
Share the base message logic and specialize how a text reminder appears. Print previews in the browser.
Ready
Run the example to see the output here.
Create an email preview subclass that prepends a subject.
Further reading in Automate the Boring Stuff with Python by Al Sweigart