Legends ofPythos
Claim your name
Objects and Classes

__init__ and setting up an object

Lesson 3 of 13

Watch the lesson5:21 · 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 value passed in.
        # Store it on this dog:
        self.name = name

# Two dogs from the same blueprint
dog1 = Dog("Rex")
dog2 = Dog("Bella")

print(dog1.name)
print(dog2.name)
Storing data on a specific instance with self
self is the name everyone gives the first parameter of __init__ (and, from the next lesson, of the other methods you write). It refers to the specific instance being set up.

When you write Dog("Rex"), Python first makes a new, empty dog. Then it runs __init__ for you, with that new dog as self and "Rex" as name. 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 on the instance with 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 (after self): owner_name, and an optional parameter balance which defaults to 100.0. Store both on the instance with 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.