Python __init__ Method, self and Attributes
The __init__ Method in Python
The __init__ method is a special function inside a class that Python runs automatically every time you make an object. Its job is to give the new object its starting attributes. "init" is short for "initialize", a fancy word for "set up at the start".
Think of it like the check-in desk of a hotel. Every guest who arrives goes through it, and each one leaves with a name on the list, a room number and a key. No guest is forgotten.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rocky = Dog("Rocky", 3)
lucky = Dog("Lucky", 5)
print(rocky.name, rocky.age)
print(lucky.name, lucky.age)Rocky 3 Lucky 5
The rules
- Write it inside the class, indented, with
def:def __init__(self, name, age): - Two underscores before
initand two after. Names with this shape are special: Python calls them for you. Programmers call them "dunder" methods, from "double underscore". - The values in
Dog("Rocky", 3)go to the parameters afterself, in order, like the arguments of a function in chapter 15. - You never call
__init__yourself.Dog("Rocky", 3)calls it.
Before and after
| By hand (last topic) | With __init__ |
|---|---|
rocky = Dog(), then rocky.name = "Rocky", then rocky.age = 3 | rocky = Dog("Rocky", 3) |
| easy to forget an attribute | every object gets every attribute |
Avoid: forgetting an argument
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rocky = Dog("Rocky")TypeError: Dog.__init__() missing 1 required positional argument: 'age'
Don't be scared of this error! It's the same as calling a function with a missing argument: __init__ needs a name and an age, and it only got a name.
Common mistake: writing _init_, with one underscore on each side. Python doesn't see it as the setup method, so it never runs, and Dog("Rocky", 3) fails with TypeError: Dog() takes no arguments.
__init__runs by itself each time you make an object, and gives it its starting attributes.