Chapter 12.3.2. Composition vs. Inheritance in Standard Python

Suppose you need to model a vehicle domain in your code. There are different kinds of vehicles, such as cars, airplanes, and submarines. There are many common attributes to all these vehicles (such as model, year, color, owner, and so on). But some attributes are relevant only for specific types of vehicles (such as number of doors for cars, wing span for airplanes, and max diving depth for submarines). You can represent this domain with the following composition-based design:

class Vehicle(object): def __init__(self): self.make = '' self.model = '' self.year = '' self.color = '' self.owner = '' class Car(object): def __init__(self): self.vehicle = Vehicle() self.doors = 0 class ...

Get Rapid Web Applications with TurboGears: Using Python to Create Ajax-Powered Sites now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.