Classes
16 min
A class bundles data (attributes) and behavior (methods) together.
__init__ is the constructor — it runs automatically when you create a
new instance, and sets up that instance's starting attributes.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says woof!"
rex = Dog("Rex")
print(rex.bark()) # Rex says woof!
Every method call on the same object shares the same self — that's what makes an object's state persistent across method calls, unlike a plain function.
self is just a name (by convention, not a keyword) for "the instance
this method was called on." When you write account.deposit(50), Python
translates that to BankAccount.deposit(account, 50) — self is always
the first parameter, filled in automatically. Every instance gets its own
independent copy of the attributes set in __init__ — account.balance
and some other BankAccount() instance's balance are completely
separate.
Complete the `Counter` class below: `__init__(self, start=0)` should set `self.count` to `start`, and `increment(self, by=1)` should add `by` to `self.count` and return `self` (so calls can be chained).
Given the `Rectangle` class below (with `__init__` and `area` already implemented), implement `is_square(self)`, returning True if width equals height.
What is `self` in a Python instance method?
You can define a class with init and instance methods, and understand how self connects a method call back to its instance's state.