All lessons
πŸ—οΈ

Classes & Objects

Object-oriented programming basics

Reward
+80 XP

Creating a class

A class is a blueprint for creating objects. Use the class keyword.

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} says woof!")

my_dog = Dog("Rex")
my_dog.bark()

__init__ and self

__init__ is the constructor β€” it runs when you create a new object. self refers to the current instance.

class Car:
    def __init__(self, brand, speed):
        self.brand = brand
        self.speed = speed

    def describe(self):
        print(f"{self.brand} goes {self.speed} km/h")

c = Car("Toyota", 180)
c.describe()

Try it yourself

Run the example below. Edit it and see what changes.

main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)

Common mistakes

  • ⚠Forgetting self as the first parameter of methods.
  • ⚠Not calling __init__ correctly β€” it's called automatically.
  • ⚠Confusing class attributes (shared) with instance attributes (per-object).