Chapter 4 · Objects and robust code

Inheritance and special methods

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 22 · Concept

A subclass gets everything its parent has

By the end of this lesson, your classes build on each other and work with print, ==, sorted and +.

from account import Account

class Savings(Account):
    def add_interest(self):
        self.balance += self.balance * 5 // 100
  • account.py holds lesson 15's Account. The import brings it in (lesson 8).
  • class Savings(Account): makes a subclass: a Savings is an Account, with more.
  • It gets every method of Account, __init__ too.
from account import Account

class Savings(Account):
    def __init__(self, owner, rate):
        super().__init__(owner)
        self.rate = rate

    def add_interest(self):
        self.balance += self.balance * self.rate // 100

s = Savings("Ada", 5)
s.deposit(200)
s.add_interest()
print(s)
print(s.rate)
from account import Account

class Savings(Account):
    def __init__(self, owner, rate):
        super().__init__(owner)
        self.rate = rate

    def withdraw(self, amount):
        if self.balance - amount < 10:
            print("Keep 10 in savings")
            return False
        return super().withdraw(amount)

s = Savings("Ada", 5)
s.deposit(50)
s.withdraw(45)
s.withdraw(30)
print(s)
print(isinstance(s, Account), isinstance(s, Savings))
a = Account("Alan")
print(isinstance(a, Savings))
from account import Account

class Checking(Account):
    def __init__(self, owner, fee):
        self.fee = fee

c = Checking("Ada", 2)
c.deposit(50)
c.withdraw(20)
print(c)
c.withdraw(40)
print(c)
import math

class Circle:
    def __init__(self, r):
        self.r = r

    def area(self):
        return math.pi * self.r ** 2

class Square:
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

shapes = [Circle(1), Square(3)]
total = 0
for shape in shapes:
    print(f"{shape.area():.2f}")
    total += shape.area()
print(f"Total: {total:.2f}")
import math

class Circle:
    def __init__(self, r):
        self.r = r

    def area(self):
        return math.pi * self.r ** 2

class Square:
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

# write the class Triangle here

shapes = [Circle(1), Square(3), Triangle(4, 3)]
total = 0
for shape in shapes:
    print(f"{shape.area():.2f}")
    total += shape.area()
print(f"Total: {total:.2f}")
class Box:
    def __init__(self, cents):
        self.cents = cents

class Money:
    def __init__(self, cents):
        self.cents = cents

    def __eq__(self, other):
        return self.cents == other.cents

a = Box(500)
b = Box(500)
print(a == b, a is b, a == a)
c = Money(500)
d = Money(500)
print(c == d, c is d)
class Money:
    def __init__(self, cents):
        self.cents = cents

    def __add__(self, other):
        return Money(self.cents + other.cents)

    def __lt__(self, other):
        return self.cents < other.cents

    def __repr__(self):
        return f"Money({self.cents})"

class Wallet:
    def __init__(self):
        self.items = []

    def add(self, money):
        self.items.append(money)

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

print(Money(250) + Money(100))
prices = [Money(500), Money(120), Money(300)]
print(sorted(prices))
w = Wallet()
w.add(Money(5))
w.add(Money(20))
print(len(w))
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

v = Vector(1, 2) + Vector(3, 4)
print(v)
print(v == Vector(4, 6))
print([Vector(0, 1), v])
# write the classes Song and Playlist here

p = Playlist("Road trip")
p.add(Song("Blue", 200))
p.add(Song("Gold", 185))
p.add(Song("Rain", 240))
print(len(p))
print(p)
class Song:
    def __init__(self, title, seconds):
        self.title = title
        self.seconds = seconds

class Playlist:
    def __init__(self, name):
        self.name = name
        self.songs = []

    def add(self, song):
        self.songs.append(song)

p = Playlist("Road trip")
p.add(Song("Blue", 200))
p.add(Song("Gold", 185))
print("Gold" in p)
print("Jazz" in p)
Terminal
Step 1 of 10A savings account

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)