Chapter 4 · Objects and robust code

Classes and objects

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

Step 1 of 21 · Concept

A class is a new kind of value

By the end of this lesson, you can write a class of your own: a bank account.

A dictionary can keep a record:

account = {"owner": "Ada", "balance": 0}

Nothing says which keys an account must have, or what you can do with one. A class describes a kind of thing once: its data and its actions. Each object made from it is one such thing, as 15 is one int.

class Account:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

a = Account("Ada")
print(a.owner, a.balance)
class Account:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        # refuse when amount is more than the balance
        return False

a = Account("Ada")
a.deposit(50)
print(a.withdraw(20))
print(a.withdraw(100))
print(a.balance)
class Account:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

    def deposit(self, amount):
        self.balance += amount

a = Account("Ada")
b = Account("Alan")
a.deposit(5)
b.deposit(20)
a.deposit(5)
print(a.owner, a.balance)
print(b.owner, b.balance)
class Account:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

    def deposit(self, amount):
        self.balance += amount

    def withdraw(self, amount):
        if amount > self.balance:
            print("Refused")
            return False
        else:
            self.balance -= amount
            return True

def transfer(src, dst, amount):
    dst.deposit(amount)

a = Account("Ada")
b = Account("Alan")
a.deposit(50)
transfer(a, b, 20)
transfer(a, b, 40)
print(a.owner, a.balance)
print(b.owner, b.balance)
class Account:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

    def deposit(self, amount):
        self.balance += amount

    def __str__(self):
        return f"{self.owner}: {self.balance}"

a = Account("Ada")
a.deposit(5)
print(a)
print(f"Statement: {a}")
print(str(a).upper())
class Book:
    def __init__(self, title, pages):
        self.title = title
        # also keep pages, and a bookmark at 0

    def read(self, n):
        # move the bookmark n pages on, not past the end
        print("reading", n)

    def __str__(self):
        # text such as Dune: page 42 of 412
        return self.title

book = Book("Dune", 412)
book.read(30)
book.read(12)
print(book)
book.read(500)
print(book)
# write the class Counter here

c = Counter("clicks")
c.increment()
c.increment()
c.increment(by=5)
print(c)
c.reset()
c.increment()
print(c)
class Account:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

a = Account("Ada")
b = Account("Alan")
c = Account("Grace")
print("Accounts:", Account.count)
Terminal
Step 1 of 8Make an 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)