← All lessons

Lesson 17

Your First Class

A class defines how objects are created and how they behave. Each instance can hold its own state.

__init__ initializes the instance. self is the instance passed to methods; attributes such as self.name belong to that object.

Call a method with object.method(). Python passes the instance automatically, so do not supply self again.

class Counter:
    def __init__(self):
        self.value = 0
    def increment(self):
        self.value += 1
c = Counter()
c.increment()
print(c.value)

Check your understanding

What does self refer to?

CHALLENGE

Define Counter with value initially 0 and increment() adding 1. Increment twice and print value.

Practice →
Next: Assertions & Edge Cases →