typestar

A class with methods in Python

The anatomy of a class: state in __init__, behavior in methods.

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

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

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount


account = BankAccount("ada", 100)
account.deposit(50)
account.withdraw(30)

How it works

  1. __init__ stores owner and balance on self.
  2. deposit and withdraw mutate that state.
  3. Invalid withdrawals raise instead of going negative.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
343
Tokens
89
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 56 seconds.

Type this snippet

Step 1 of 5 in Classes, step 39 of 72 in Language basics.

← Previous Next →