After this lesson every object you create will start life with the attributes it needs, and you will know exactly what self means.
The problem with setting attributes by hand
In the previous lesson you made an object and then added attributes one line at a time. That works, but it is easy to forget one. A product with no price will crash a program later, far from the mistake. It would be better if a product could not exist without a name and a price.
Python solves this with a special method called __init__ (two underscores on each side, said "dunder init"). Python calls it automatically every time you create an object.
Writing __init__
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
pen = Product("Pen", 2.5)
notebook = Product("Notebook", 4.0)
print(pen.name, pen.price)
print(notebook.name, notebook.price)Pen 2.5
Notebook 4.0Read Product("Pen", 2.5) as two steps that Python does for you. First it builds an empty object. Then it calls __init__ on that object, passing the object as self followed by your arguments "Pen" and 2.5. The two lines inside copy those values onto the object.
What self really is
self is just a parameter name, and the object being worked on is what arrives in it. You can prove it by printing whether self is the very same object that you get back:
class Probe:
def __init__(self):
self.seen_as_self = self
p = Probe()
print(p.seen_as_self is p)TrueUsing the name self is a universal habit that every Python programmer expects. Technically another name would work, but do not do that, because it makes your code harder for others to read.
The line self.name = name has two different name words. The one after the dot is the attribute stored on the object. The one on the right is the parameter. They often match, which is tidy, but they are separate things. If you forget self. the value is stored in an ordinary local variable that disappears when __init__ ends.
Default values and calculated attributes
Parameters of __init__ can have defaults, and __init__ can do work, such as setting up an empty list:
class Product:
def __init__(self, name, price, stock=0):
self.name = name
self.price = price
self.stock = stock
self.tags = []
mug = Product("Mug", 6.0)
lamp = Product("Lamp", 18.0, stock=12)
print(mug.stock, lamp.stock)
mug.tags.append("kitchen")
print(mug.tags, lamp.tags)0 12
['kitchen'] []Creating the list inside __init__ means each product gets its own list. That is why adding a tag to the mug does not touch the lamp.
Methods that use the stored data
Once the data is set up reliably, methods can depend on it:
class Product:
def __init__(self, name, price, stock=0):
self.name = name
self.price = price
self.stock = stock
def stock_value(self):
return self.price * self.stock
def sell(self, quantity):
self.stock = self.stock - quantity
lamp = Product("Lamp", 18.0, stock=12)
print(lamp.stock_value())
lamp.sell(5)
print(lamp.stock, lamp.stock_value())216.0
7 126.0Notice that sell changes the object and returns nothing. Methods that update state are common in classes.
When you forget an argument
Because __init__ has required parameters, Python stops you from making an incomplete object:
broken = Product("Pen")TypeError: __init__() missing 1 required positional argument: 'price'That is the safety net the previous lesson was missing.
A video version of this topic is in the video course at /learn/python/.
Common mistakes
- Forgetting
self.on the left. Writingname = nameinside__init__stores nothing on the object. - Leaving
selfout of the parameter list.def __init__(name, price)makes Python treat the first value as the object, which causes confusing errors. - Passing
selfwhen creating an object. WriteProduct("Pen", 2.5), neverProduct(self, "Pen", 2.5). - Returning a value from
__init__. It must returnNone. Do the setup and stop. - Using a mutable default such as
tags=[]. A default list is created once and shared by every object. UseNoneas the default and create the list inside the method, or just create the empty list as shown above.
Exercise
Write a class Student with an __init__ that takes name and an optional grades list (default None, which should become a new empty list). Add a method add_grade(value) and a method average() that returns the average. Create one student, add grades 70, 80 and 90, and print the average.
Show one possible answer
class Student:
def __init__(self, name, grades=None):
self.name = name
self.grades = grades if grades is not None else []
def add_grade(self, value):
self.grades.append(value)
def average(self):
return sum(self.grades) / len(self.grades)
asha = Student("Asha")
for g in (70, 80, 90):
asha.add_grade(g)
print(asha.average())80.0Key points
- __init__ runs automatically each time you create an object, and it is where you set up the starting attributes.
- self is the object being created or used. Python passes it in as the first argument, so you never supply it yourself.
- Arguments you pass to the class, such as Product('Pen', 2.5), are handed on to __init__.
- Parameters of __init__ can have default values, just like any other function.
- __init__ does not return a value. Its job is only to set up self.