Python __init__ Is NOT a Constructor?! Then What Is It?

Python基础 Oct 21, 2022

Python __init__: The Impostor Constructor

If you come from Java or C++, you probably think __init__ is Python's constructor. It gets called automatically when you create an object, right? Well... not exactly. The REAL constructor is __new__.

Think of it this way: __new__ is the construction crew that builds the house (allocates memory, creates the bare object), while __init__ is the interior decorator that furnishes it (sets attributes). Without the construction crew, there's no house to decorate.

95% of Python developers will never need to override __new__. But for singleton patterns, metaclasses, or immutable type subclasses - you need __new__. It's like knowing how to bake a cake in the microwave: you probably won't do it, but it's good to know it's possible.

Bottom line: __init__ is the decorator, __new__ is the builder. When the interviewer asks, just say "are you asking about the decorator or the builder?"

Tags