Paul's Python CoursePPC

Composition

Not met yet

Composition builds an object out of other objects it keeps in its attributes: a shed has a list of bikes; a car has an engine. Inheritance says one thing is a kind of another. Ask "is a" or "has a": inherit when "is a" is true, compose when "has a" is. The shed holds the very bikes you added, not copies.

Try it

main.py
class Shed:
    def __init__(self):
        self.bikes = []

    def add(self, bike):
        self.bikes.append(bike)

    def __len__(self):
        return len(self.bikes)

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks an object automatically gets the methods of the objects it keeps in its attributes.
  • Thinks storing an object in another object's attribute makes a copy of it.

Where it comes up