Lesson 1 of 10

Your first class

Goal

Data and behavior in one place

01

Explanation

A class is a template that bundles data with the functions that work on it, and you create objects from it. The __init__ method runs every time an object is created and sets its starting values.

self is the object itself, so self.balance = 0 means "the balance of this account". Every method in the class takes self as its first parameter.

The real payoff is that the rule lives with the data. Nobody can push the balance below zero, because the only way to change it goes through a method that checks.

02

Your task

Write an Account class whose balance starts at zero, give it deposit and withdraw, and make any withdrawal larger than the balance raise a ValueError.

Checks

5 checks
  1. A new account starts at zero
  2. It stores the owner's name
  3. Deposits increase the balance
  4. Withdrawals decrease the balance
  5. Overdrawing raises ValueError and leaves the balance unchanged
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.