Lesson 22 of 30

In progress

Course progress

Python

__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 self refers 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
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.

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
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
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.

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
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.

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
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.

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
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.

__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
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.

__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

  • self is 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?
No. Python requires `__init__` to return `None`; returning anything else raises `TypeError`. If you need a different constructor, write a class method such as `from_dict` that builds and returns an instance.
What is the difference between __str__ and __repr__?
`__str__` is the readable form for users, used by `print` and f-strings. `__repr__` is the unambiguous form for developers, used in lists, debugging and the interactive prompt. If you only define one, define `__repr__`.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.