Hone

Lessons · Python · __init__ and self

__init__ runs when an object is built; self is that object

__init__ is the method Python calls on a new object. self is the object being built, and self.name = name stores a value on it.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Every object needs its starting values: the account's balance, the player's position, the order's items. __init__ is where they are set, once per object, so no object starts half-made.

How to think about it

Ask: what must every one of these know from the moment it exists? Those are the parameters of __init__, each stored as self.something. Anything not stored on self is gone when __init__ ends.

Worked example

class Dog:
The kind of thing.
    def __init__(self, name):
self is filled in by Python; you pass name.
        self.name = name
Stored on this one object.
        self.tricks = []
A fresh list per object, not shared.
rex = Dog('Rex')
One argument from you; self comes free.
print(rex.name, rex.tricks)
Rex []

Your turn

Store the starting balance on the object.

class Account:
    def __init__(self, balance):
         = balance

The trap

def __init__(name): without self. Python still passes the object first, so the call fails with 'takes 1 positional argument but 2 were given'.

Practise __init__ and self on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.