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
__init__stores owner and balance onself.depositandwithdrawmutate that state.- Invalid withdrawals raise instead of going negative.
Keywords and builtins used here
BankAccountclassdefdepositifraiseselfwithdraw
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.
Step 1 of 5 in Classes, step 39 of 72 in Language basics.