Learn Python
>>> oop_fundamentals.constructor

The __init__() Constructor in Python

#concept

__init__() is a special method Python calls automatically every time a new instance is created, making it the natural place to set up an object's initial data. Its first parameter is always self, referring to the instance being created — everything assigned to self inside __init__() becomes that instance's own attribute.

#how it works
1

Define __init__(self, ...)

self is always the first parameter, followed by any setup parameters.

2

Python calls it automatically

The moment ClassName(...) is written — it’s never called directly by name.

3

Arguments are forwarded

Extra values passed to ClassName(...) go straight to __init__().

4

self.attribute = value stores data

Creates that attribute on the specific instance being built.

5

Each instance stays independent

Changing one instance’s data never affects another.

#example
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
 
rex = Dog("Rex", 3)
bella = Dog("Bella", 5)
 
print(rex.name, rex.age)
print(bella.name, bella.age)
Output
Rex 3
Bella 5
1Dog("Rex", 3) calls __init__(self, "Rex", 3) behind the scenes, with self automatically bound to the new instance being created.
2self.name = name and self.age = age store those values on that specific instance.
3bella = Dog("Bella", 5) creates a completely separate instance, with its own name and age.
4Printing each instance’s attributes shows they hold independent data, even though both came from the same class.
#use cases
Requiring certain data up front whenever an object is created, like a User needing a username
Setting sensible default values for optional attributes
Validating input as an object is constructed, before any other code can use it
Running any one-time setup logic an object needs the moment it comes into existence

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.