Python Classes and Objects: __init__ and Instances
A class is a blueprint for objects, the heart of object-oriented programming (OOP) in Python. Each object made from it is an instance with its own data.
A method called __init__ sets up each new instance. Read
Functions and Dictionaries
first.
Define a class and create an object
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
ada = Player("Ada", 12)
print(ada.name)
print(ada.score)
Player("Ada", 12) creates a new object and runs __init__ on it. Inside
__init__, self is that new object. self.name = name stores a value on
the object. A value stored this way is an attribute. Read it back with a
dot: ada.name.
Make several instances
Every instance keeps its own attributes. Changing one object leaves the others alone.
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
ada = Player("Ada", 12)
ben = Player("Ben", 7)
ben.score = 9
print(ada.name, ada.score)
print(ben.name, ben.score)
Ada still has 12. Only Ben's score changed to 9.
Forgetting self in __init__
Without self., the value goes into a local variable. It disappears when
__init__ ends, so the object never gets the attribute.
class Player:
def __init__(self, name):
player_name = name # a local variable, not an attribute
ada = Player("Ada")
print(ada.name) # this line raises AttributeError
The fix is self.name = name.
Print an object nicely with __repr__
Printing a plain object shows something like <__main__.Player object at 0x…>.
Add a __repr__ method that returns the text you want instead.
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return f"Player({self.name!r}, {self.score})"
print(Player("Ada", 12))
print([Player("Ada", 12), Player("Ben", 7)])
Lists of objects print with it too. __repr__ is a method: a function
that belongs to the class. Methods and self
covers them.
Note: Name classes in CapWords, like Player or BankAccount. Name
attributes in snake_case, like high_score.
See also: Methods and self, Inheritance.
Your turn
Finish __init__ so each Book stores its title and pages.
class Book:
def __init__(self, title, pages):
# add two lines: store title and pages on self
pass
book = Book("Dune", 412)
print(book.title)
print(book.pages)
Expected output
Dune
412