Sub topic 2
Initializing objects with __init__ and self
This chapter assumes you can write Python functions with default arguments and that you know what a class statement looks like. It covers what happens when you call a class, what self refers to, and how to write an __init__ that is safe to use.
What happens when you call a class
Calling a class, as in Dog("Rex", 3), runs two steps:
- Python calls
__new__, which allocates a new, empty instance. You rarely write this method yourself. - Python calls
__init__on that instance, passing along the arguments you gave.
__init__ is the initializer. It does not create the object. It receives an object that already exists and fills in its starting state.
What self is
self is the first parameter of every instance method, including __init__. It is bound to the instance being worked on. The name is a convention, not a keyword, but every Python programmer expects it.
You never pass self yourself. Python passes it when you call a method through an instance.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
rex = Dog("Rex", 3)
print(rex.name, rex.age) # Rex 3
print(vars(rex)) # {'name': 'Rex', 'age': 3}The line self.name = name creates an instance attribute named name on the object and stores the argument in it. The bare name is a local variable that disappears when __init__ returns. vars(rex) shows the instance's own attributes as a dictionary.
Defaults and validation
__init__ is a good place to set defaults and to reject bad input, so an object is never left half-built.
class Counter:
def __init__(self, start=0):
if start < 0:
raise ValueError("start must be non-negative")
self.count = start
self.history = [] # a fresh list for every instance
def increment(self):
self.history.append(self.count)
self.count += 1
a = Counter()
b = Counter(10)
a.increment()
print(a.count, b.count) # 1 10
print(a.history) # [0]
print(b.history) # []If __init__ raises an exception, the call fails and you get no object. Each instance has its own history list because the list is created inside __init__ on every call.
Avoid mutable default arguments such as def __init__(self, items=[]). Python evaluates the default once, when the function is defined, so every instance would share one list. Use None as the default and create the list inside the method.
class Basket:
def __init__(self, items=None):
self.items = list(items or [])
x, y = Basket(), Basket()
x.items.append("apple")
print(y.items) # []Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Omitting `self` from the parameters | `TypeError` about too many positional arguments | Write `def __init__(self, ...)` |
| Writing `name = name` instead of `self.name = name` | The value is lost, and later access raises `AttributeError` | Assign to `self.` |
| Returning a value from `__init__` | `TypeError` | Return nothing |
| Misspelling `__init__` | The method is never called, and extra arguments raise `TypeError` | Check the double underscores on both sides |
The return-value error looks like this:
class Bad:
def __init__(self):
return 5
try:
Bad()
except TypeError as exc:
print(exc) # __init__() should return None, not 'int'Exercise
What is wrong with this class, and how do you fix it? class Playlist: def _init_(self, name, songs=[]): self.name = name self.songs = songs
Show answer
The default list is created once, when the function is defined, so every Playlist created without a songs argument shares the same list. Adding a song to one playlist adds it to all of them. Use songs=None as the default and write self.songs = list(songs or []) inside _init_, which gives each instance its own list.