Latticework

Command Palette

Search for a command to run...

Python

Classes

16 min

Explanation

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!
Try it

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.

Loading editor…
Explanation

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.

Exercise

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).

Exercise

Given the `Rectangle` class below (with `__init__` and `area` already implemented), implement `is_square(self)`, returning True if width equals height.

Quiz

What is `self` in a Python instance method?

Checkpoint

You can define a class with init and instance methods, and understand how self connects a method call back to its instance's state.