Browser lab18 min+60 XP

__init__ and self

Set up every new object automatically, with the data it needs from the start.

0% done

Code runs right here in your browser. Nothing to install.

TASK 1

Learn it

Key idea

__init__ sets up every new object, and self means this object.

Key words
the new Hero objectHero("Nova")__init__(self, name)runs automaticallyself.name = "Nova"self.health = 100self.items = []
Creating a Hero runs __init__, which fills in the new object.

Setting attributes one by one is slow and easy to forget. The special method __init__ (two underscores each side, called "dunder init") runs automatically every time you create an object. Use it to set up the attributes.

Every method gets the object itself as its first parameter, called self by convention. Inside __init__, self.name = name means "store the name argument on this object".

Arguments you pass when creating the object go to __init__: Hero("Nova", 100) calls __init__(self, "Nova", 100). Python fills in self for you.

Real life linkA cookie cutter makes every biscuit the same shape, but each biscuit gets its own icing. __init__ gives each new object its own details.
Example code
class Hero:
    def __init__(self, name, health=100):
        self.name = name
        self.health = health
        self.items = []

nova = Hero("Nova")
kai = Hero("Kai", 80)
nova.items.append("torch")
print(nova.name, nova.health, nova.items)
print(kai.name, kai.health, kai.items)
TASK 2

Try it yourself

+10 XP

Write a class Spaceship whose __init__ takes a name and a fuel amount (default 100) and also sets passengers to 0. Create two ships and print Comet fuel 100 passengers 0 and Nebula fuel 45 passengers 0.

Create a free account to start this lab

Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.

TASK 3

Capture the flag

+10 XP

What is the first parameter of every method conventionally called?

Create a free account to start this lab

Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.

HOMEWORK

Student records

+20 XP

Write a class Student with __init__(self, name, year) that also creates an empty marks list. Create two students, append some marks to each, and print each student's name, year and their marks list, like Ava (Year 10): [72, 88].

Create a free account to start this lab

Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.