Lesson 22 of 30
In progress
__init__, self and shared state
Understand what self actually refers to, why __init__ runs on creation, and why a list in the class body is shared by every object.
Two objects from the same class can share a value you never meant to share. The cause is always the same line: an attribute created in the class body instead of inside __init__.
What you will learn
- Trace what
selfrefers to at each call. - Use
__init__for setup, including defaults. - Tell instance attributes from class attributes, and print objects readably.
self is the object, passed automatically
When you call ana.describe(), Python turns it into Student.describe(ana). The object is passed as the first argument, and the parameter that receives it is conventionally named self.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def describe(self):
return f"Student: {self.name}"
ana = Student("Ana")
ravi = Student("Ravi")
print(ana.describe())
print(ravi.describe())
print(Student.describe(ana))
Press Run to see the output.
The last line calls the method through the class and passes the object explicitly. It produces the same text, which makes the mechanism visible. self is not a keyword; it is a parameter name. The convention is so strong that using another name confuses every reader, so keep self.
Inside __init__, self.name = name creates an attribute on that particular object. The right-hand name is the parameter; the left-hand one is the attribute. When they differ, the code stays readable:
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
Press Run to see the output.
init sets up, it does not create
__init__ runs after the object exists. Its job is to put the object into a valid starting state: assign attributes, validate arguments, open nothing you cannot close.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def tick(self):
if self.remaining > 0:
self.remaining -= 1
return self.remaining
short = Timer(3)
print(short.tick(), short.tick(), short.tick(), short.tick())
default = Timer()
print(default.remaining)
Press Run to see the output.
The default 60 makes Timer() valid. The validation runs for every instance, so an invalid timer cannot exist at all. That is stronger than checking later at each use.
Instance attributes versus class attributes
An attribute assigned through self belongs to one object. An attribute assigned in the class body belongs to the class and is visible through every object.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def add(self, song):
self.songs.append(song)
road = Playlist()
study = Playlist()
road.add("Highway")
print(road.songs)
print(study.songs)
Press Run to see the output.
study.songs contains the song too, because both objects read the same class-level list. The fix is to create the list per object:
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def add(self, song):
self.songs.append(song)
road = Playlist()
study = Playlist()
road.add("Highway")
print(road.songs)
print(study.songs)
Press Run to see the output.
vars(obj) or obj.__dict__ shows exactly which attributes one object stores. It is the quickest way to confirm that two instances are independent, and to spot an attribute you meant to set in __init__ but forgot. An attribute that appears in one object’s dictionary and not the other’s is a real difference, not a printing quirk.
Class attributes are fine for genuine constants shared by all instances, such as currency = "INR" or max_tracks = 100. They are dangerous for mutable containers that each object should own.
The same rule catches the mutable default argument from lesson 17, and for the same reason: the value is created once and reused.
Printing objects with str and repr
__str__ controls what print shows. __repr__ controls the developer-facing representation, and it is what you see in a list or at the prompt.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def __str__(self):
return f"{self.name} ({len(self.songs)} songs)"
def __repr__(self):
return f"Playlist(name={self.name!r}, songs={len(self.songs)})"
mix = Playlist("Road trip")
mix.songs.append("Highway")
print(mix)
print(repr(mix))
print([mix])
Press Run to see the output.
__str__ is for people reading output; __repr__ should be unambiguous enough to debug. A common shortcut is to define __repr__ only, because print falls back to it, but a friendly __str__ is worth the two lines for anything shown to a learner.
Defining __init__ with a mutable default, def __init__(self, tags=[]), recreates the shared-list bug at construction time. Use tags=None and assign a fresh list inside, exactly as you would for a plain function.
Write a Playlist class whose constructor takes a name. Add add(song), __len__ returning the number of songs, and __str__. Create two playlists, add different songs, and print both plus len() of each.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
def add(self, song):
self.songs.append(song)
def __len__(self):
return len(self.songs)
def __str__(self):
return f"{self.name}: {', '.join(self.songs) or 'empty'}"
road = Playlist("Road")
study = Playlist("Study")
road.add("Highway")
study.add("Lo-fi")
print(road, len(road))
print(study, len(study))
Press Run to see the output.
__len__ is what makes len(road) work. The or 'empty' handles the case where the join produces an empty string, so the output still reads like a sentence.
Recap
selfis the object, passed automatically as the first argument.__init__validates and assigns; it runs for every new object.- Mutable state belongs in
__init__, never in the class body or a default argument.
Next, you will add methods that change state safely, and expose computed values with properties.
Can __init__ return a value?
What is the difference between __str__ and __repr__?
Progress is saved in this browser only. No account, no email.