init in Python: How Object Initialisation Works

__init__ is the method Python calls automatically when you create an object. It’s where you set the object’s initial attributes.

class Car: def __init__(self, make, model): self.make = make self.model = modelcar = Car("Toyota", "Corolla") print(car.make) # Toyota

You never call it directly. Writing Car("Toyota", "Corolla") runs it, and the arguments you pass go to its parameters — all of them except self, which Python supplies.

⚠️ And it isn’t a constructor, strictly speaking. The object already exists by the time __init__ runs; its job is to fill it in. This guide covers self, default values, inheritance with super(), the mutable default trap, and when a dataclass makes __init__ unnecessary.

The short version
First parameterAlways self — Python passes it for you
ReturnsMust return None — anything else raises
CalledAutomatically, when you instantiate the class
The trapA mutable default is shared by every instance
Often unnecessaryA @dataclass writes it for you

The syntax

class ClassName: def __init__(self, parameter1, parameter2): self.attribute1 = parameter1 self.attribute2 = parameter2

Two underscores on each side — that’s what makes it a dunder method, one Python calls automatically. Writing _init_ or init gives you an ordinary method that never runs on its own.

self is not optional

class Broken: def __init__(): passBroken() # TypeError: Broken.__init__() takes 0 positional arguments but 1 was given

self is the object being initialised. Python passes it automatically as the first argument, so the method has to declare a parameter to receive it.

⚠️ The name self is convention, not syntax — the first parameter could be called anything. But every Python codebase uses self, and using something else will confuse every reader.

And self.x = x is what makes the value stick:

class Person: def __init__(self, name): name = name # local variable — lost immediately self.name = name # attribute on the object — persists

Without self., you’re assigning to a local variable that disappears when the method ends.

It must return None

class Bad: def __init__(self): return 5Bad() # TypeError: __init__() should return None, not 'int'

__init__ initialises; it doesn’t produce anything. A bare return to exit early is fine — returning a value isn’t.

Default values

class Car: def __init__(self, make, model, year=2024): self.make = make self.model = model self.year = yearCar("Toyota", "Corolla") # year is 2024 Car("Toyota", "Corolla", 2020) # year is 2020

Parameters with defaults have to come last — Python can’t tell which argument you meant otherwise.

And missing a required one raises immediately:

Car() # TypeError: Car.__init__() missing 2 required positional arguments: 'make' and 'model'

⚠️ The mutable default trap

The mutable default trap in __init__: using an empty list as a default shares one list across every instance, while using None and creating the list inside works correctly

This is the sharpest bug in the whole topic, and it shares data between objects that should be independent.

class Basket: def __init__(self, items=[]): self.items = itemsa = Basket() b = Basket()a.items.append("apple") print(b.items) # ['apple'] ← b was never touched

Default arguments are evaluated once, when the class is defined — so there is one list, shared by every instance created without an explicit argument.

The fix is the standard =None pattern:

class Basket: def __init__(self, items=None): self.items = items if items is not None else []a = Basket() b = Basket() a.items.append("apple") print(b.items) # [] ← independent

⚠️ None is immutable, which is why it’s safe as a default. The new list is created inside the method, on every call. Our guide on None in Python covers why.

The related trap: class attributes

class Wrong: tags = [] # class attribute — one, shareddef __init__(self): self.own = [] # instance attribute — one per objecta, b = Wrong(), Wrong() a.tags.append("x") a.own.append("x")print(b.tags) # ['x'] ← shared print(b.own) # [] ← independent

Anything defined directly in the class body belongs to the class, not to each object. ⚠️ It’s fine for constants; it’s a bug for anything that changes.

Inheritance and super()

class Animal: def __init__(self, name, age): self.name = name self.age = agedef speak(self): print(f"{self.name} makes a sound")class Dog(Animal): def __init__(self, name, age, breed): super().__init__(name, age) # run the parent's __init__ self.breed = breeddog = Dog("Fido", 3, "Labrador") print(dog.name) # Fido ← from Animal print(dog.breed) # Labrador ← from Dog dog.speak() # Fido makes a sound

Defining __init__ in the child replaces the parent’s — super().__init__() is what runs it as well.

⚠️ Forgetting it loses the parent’s attributes silently:

class Dog(Animal): def __init__(self, breed): self.breed = breed # no super() calldog = Dog("Labrador") dog.name # AttributeError: 'Dog' object has no attribute 'name'

The class instantiates without error. The failure comes later, wherever something uses name.

And a child doesn’t need its own __init__ — without one, it inherits the parent’s whole.

*args and **kwargs

They collect extra arguments, and neither is the first parameter — self always is.

class Flexible: def __init__(self, name, **kwargs): self.name = name for key, value in kwargs.items(): setattr(self, key, value) # creates real attributesobj = Flexible("Ana", height=180, city="Lisbon") print(obj.height) # 180 print(obj.city) # Lisbon

⚠️ The setattr() loop is what makes them attributes. Writing self.kwargs = kwargs stores a dictionary instead — and obj.height then raises AttributeError, because the value lives at obj.kwargs["height"].

And setattr() is a built-in function, not a method:

setattr(obj, "colour", "red") # correct obj.setattr("colour", "red") # AttributeError

__new__ and __init__

Two methods run when you create an object, in this order:

class Demo: def __new__(cls, *args): print("__new__ runs first") return super().__new__(cls)def __init__(self, value): print("__init__ runs second") self.value = valueDemo(5) # __new__ runs first # __init__ runs second

__new__ creates the object; __init__ fills it in. ⚠️ This is why __init__ isn’t a constructor — by the time it runs, the object exists.

You’ll almost never write __new__. It matters for immutable types and for patterns like singletons — for ordinary classes, __init__ is all you need.

When you don’t need __init__ at all

Dataclasses

Since Python 3.7, a decorator writes it for you:

from dataclasses import dataclass@dataclass class Point: x: int = 0 y: int = 0p = Point(1, 2) print(p) # Point(x=1, y=2) ← readable repr, free print(Point(1, 2) == Point(1, 2)) # True ← comparison, free

The same class written by hand needs __init__, __repr__ and __eq__ — about fifteen lines for what the decorator does in four.

⚠️ And dataclasses refuse the mutable default outright:

@dataclass class Bad: tags: list = [] # ValueError: mutable default <class 'list'> for field tags is not allowedfrom dataclasses import field@dataclass class Good: tags: list = field(default_factory=list) # a new list per instance

Python catches at class-definition time the bug that plain classes let through silently. Use a dataclass when the class mostly holds data — it’s less code and safer.

__repr__ is worth adding either way

class Point: def __init__(self, x, y): self.x = x self.y = ydef __repr__(self): return f"Point({self.x}, {self.y})"print(Point(1, 2)) # Point(1, 2) # without __repr__: <__main__.Point object at 0x7f...>

⚠️ The default representation tells you nothing — and it’s what appears in every log line and every debugger. A three-line __repr__ pays for itself the first time something goes wrong.

⚠️ On a server: the shared-state problem

The mutable default trap changes character in a long-running process.

class Session: def __init__(self, user, cart=[]): # one list, forever self.user = user self.cart = cart

In a script that runs once, this is a curiosity. In a web application handling requests for days, every session shares the same cart — which is a memory leak and a data leak between users at the same time.

⚠️ And it never raises. The list grows quietly until memory runs out, and on shared hosting the process is killed with no traceback. The symptom is a worker that dies every few days for no apparent reason.

Two habits that prevent it:

Never use a mutable default — =None plus a check inside, or a dataclass with field(default_factory=list).

And keep __init__ cheap. Database connections, file reads and API calls inside it mean every instantiation pays that cost — in a request handler, that’s per request.

A worker that dies every few days is usually shared state

A mutable default grows across every request until memory runs out — and on shared hosting the process is killed with no traceback to explain it. Copahost VPS plans give you dedicated memory, root access, and logs that survive the crash. From €3.99/month, with snapshots.

See VPS plans

Frequently asked questions

What is __init__ in Python?

A special method Python calls automatically when you create an object, used to set its initial attributes. You never call it directly — instantiating the class runs it, with the arguments you passed.

Why does every method need self?

Because self is the object being worked on, and Python passes it as the first argument automatically. Without a parameter to receive it, you get TypeError: takes 0 positional arguments but 1 was given. ⚠️ The name is convention — but every codebase uses self.

Is __init__ a constructor?

Not strictly. __new__ creates the object; __init__ initialises it — by the time __init__ runs, the object already exists. In practice the distinction rarely matters, because you’ll almost never write __new__.

Why do all my objects share the same list?

Because a mutable default is evaluated once, when the class is defined — so every instance created without an explicit argument shares it. Use =None and create the list inside the method, or a dataclass with field(default_factory=list).

What’s the difference between a class attribute and an instance attribute?

A class attribute is defined in the class body and shared by every object. An instance attribute is created with self. inside __init__ and belongs to that object alone. ⚠️ Class attributes are fine for constants and a bug for anything that changes.

Do I need __init__ in a child class?

Only if it adds something. Without one, the child inherits the parent’s whole. If you define one, call super().__init__() inside it — otherwise the parent’s attributes are never set, and the failure appears later as AttributeError.

Can __init__ return a value?

No. It must return None — anything else raises TypeError: __init__() should return None. A bare return to exit early is allowed; returning a value isn’t.

What do *args and **kwargs do in __init__?

They collect extra positional and keyword arguments. ⚠️ The first parameter is always self, never *args. And to turn keyword arguments into real attributes you need a setattr() loop — storing the dictionary means obj.height raises, because the value is at obj.kwargs["height"].

How do I set an attribute after the object is created?

Directly with obj.attribute = value, or with the built-in setattr(obj, "attribute", value) when the name is in a variable. ⚠️ setattr is a function, not a method — obj.setattr(...) raises AttributeError.

When should I use a dataclass instead of writing __init__?

When the class mostly holds data. @dataclass generates __init__, __repr__ and __eq__ from the annotated fields — four lines instead of fifteen. It also refuses mutable defaults at class-definition time, catching the bug a plain class lets through.

Why does printing my object show a memory address?

Because the class has no __repr__. The default shows only the type and address, which is what appears in every log line. A three-line __repr__ returning something like Point(1, 2) makes debugging considerably easier.

Should I put database connections in __init__?

Generally not. Every instantiation pays that cost — in a request handler, that’s once per request. ⚠️ Keep __init__ cheap: assign attributes and validate. Do the expensive work lazily, on first use, or share a connection pool.

Conclusion

__init__ runs when you create an object, and its job is to fill in the attributes. Everything else about it follows from two facts.

self is the object, passed automatically as the first argument — which is why every method declares it, and why self.name = name persists while name = name doesn’t. And __init__ must return None, because it initialises rather than produces.

The bug worth memorising is the mutable default. def __init__(self, items=[]) creates one list shared by every instance, because defaults are evaluated once when the class is defined. ⚠️ In a script it’s a curiosity; in a web process it’s a memory leak and a data leak at once — and it never raises.

And often you don’t need to write __init__ at all. A @dataclass generates it along with __repr__ and __eq__, in a quarter of the lines — and it refuses the mutable default outright, catching at definition time what a plain class lets through silently.

Share the Post:
Picture of Gustavo Gallas

Gustavo Gallas

Graduated in Computing at PUC-Rio, Brazil. Specialized in IT, networking, systems administration and human and organizational development​. Also have brewing skills.