Python · Advanced · 13 min
Classes and instances
Model related data and behavior with a small class.
Create an instance
__init__ sets the initial state of each new instance. self refers to the instance receiving the method call.
class Account:
def __init__(self, owner):
self.owner = owner
account = Account("Ada")
print(account.owner)Output
Ada
Add behavior
An instance method can read and update that instance state while keeping the rule close to the data.
class Counter:
def __init__(self):
self.value = 0
def add(self):
self.value += 1
counter = Counter()
counter.add()
print(counter.value)Output
1
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Model a wallet
Complete Wallet so deposit adds to balance. Keep the supplied calls and display 15.
Update self.balance inside deposit().
Classes and instances
- Read both classes and instances examples before answering.
- Run the task, compare its exact output, and revise the code if needed.