Python theorytheory 0/50 · 0%
OOP · easy

19. Classes and objects

Defining classes with __init__ and methods.

A class bundles state and behavior. `__init__` initializes new instances, and `self` refers to the instance within methods.

python
class Wallet:
    def __init__(self, address, balance=0):
        self.address = address
        self.balance = balance

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

w = Wallet("0xabc")
w.deposit(5)

`__repr__` controls how an object prints for debugging; `__eq__` controls `==` comparisons. Without them, instances compare by identity and print as `<Wallet object at 0x...>`.

Check your understanding

  1. 1. What is `self` inside a method?

  2. 2. When does `__init__` run?

  3. 3. What controls how `print(obj)` displays an instance?