Bitpath

Lesson 2 · Unit 07

Objects working together

One object holds another, or one class builds on another

13 exercisesabout 3 min

What you practise

  • One object holding another, inheritance and super(), overriding a method, @property, @dataclass for the boilerplate

Try a question from this lesson

Pick one

An attribute can hold any value, even another object. What does this program show?

Python
class Engine:
    def start(self):
        return "vroom"

class Car:
    def __init__(self):
        self.engine = Engine()

    def start(self):
        return self.engine.start() + "!"

print(Car().start())
Hint

Line 7 runs when the car is made. What does line 10 ask the engine to do?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

An object can hold objects

Attributes can hold objects of other classes, or a whole list of them.

A car has an engine. A playlist has songs. A shop has items. Say "has a" out loud: if the sentence is true, one object should hold the other.

Each class stays small and does one job.

Python
class Song:
    def __init__(self, title):
        self.title = title

class Playlist:
    def __init__(self):
        self.songs = []   # Song objects

mix = Playlist()
mix.songs.append(Song("Blue"))
print(mix.songs[0].title)  # Blue

Concept

Inherit, override, super

A child class starts with everything its parent has.

Define a method again in the child and the child's version is used instead. That is called overriding.

Inside the child, super() reaches the parent's version, so you can build on it without copying it.

Python
class Animal:
    def speak(self):
        return "hm"

class Dog(Animal):
    def speak(self):          # override
        old = super().speak()
        return old + " Woof"

print(Dog().speak())  # hm Woof

Concept

@dataclass

Many classes only hold data, and their __init__, __repr__ and __eq__ all look alike.

@dataclass writes those three for you. You list the attributes, each with the type you expect after a colon.

Python
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p = Point(1, 2)
print(p)                 # Point(x=1, y=2)
print(p == Point(1, 2))  # True

9 more exercises in the app

  • 4× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy