Legends ofPythos
Claim your name
Objects and Classes

__init__ and setting up an object

Lesson 3 of 13

Watch the lesson1:15 · with Torsten
__init__ is a special method that runs automatically when you create a new object from your class.

Mental model: Think of __init__ as the assembly line at a factory. The blueprint (your class) says what parts exist, but __init__ is where each specific unit gets its serial number and configuration.
Why it matters: Real programs are full of things that need setup: a bank account needs an owner's name; a game character needs health points. Without __init__, you'd have to manually set every attribute after creating the object, which is error-prone and messy.

The self parameter

class Dog:
    def __init__(self, name):
        # 'name' is the input argument
        # we save it to THIS specific dog object as an attribute
        self.name = name 

    def speak(self):
        print(f"{self.name} says Woof!")

# Create two different dogs using the same blueprint.
dog1 = Dog("Rex")
dog2 = Dog("Bella")

dog1.speak()
print(dog2.name)
Storing data on a specific instance with self
self is a convention for the first parameter of every method. It refers to the specific instance that called it.

When you call dog1.speak(), Python passes dog1 as the value of self. This allows different objects created from the same class (like Rex and Bella) to hold completely independent data without stepping on each other's toes.

Setting up with defaults

class Player:
    def __init__(self, name="Hero", level=1):
        self.name = name
        self.level = level

guest_player = Player()
custom_player = Player("ShadowKnight", 42)
print(guest_player.name) # Hero
print(custom_player.name)# ShadowKnight
__init__ parameters can have default values just like regular functions
Default values let you create objects with minimal information. The guest_player example shows how Python fills in the gaps when you don't provide arguments.

Your turn

0 of 3 solved

Exercise 1

+35 XP
Create a class called Car. Its __init__ method should take one parameter, brand (after self), and store it as an attribute on the instance using self.brand = brand.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+35 XP
Create a class called Account. Its __init__ method should take two parameters: owner_name, and an optional parameter balance which defaults to 100.0. Store both on the instance using self.owner_name = owner_name and self.balance = balance.
Write your Python here.

Run your code to check it against the tests.

Exercise 3

+35 XP
Create a class called Book. Its __init__ should take three parameters: title, and two optional ones, author (defaulting to 'Unknown') and year_published (defaulting to 2000). Store all of them as instance attributes using the exact same names.
Write your Python here.

Run your code to check it against the tests.