Python Constructors – __init__() and __new__() Explained
Introduction – Why Use Constructors in Python?
When you create an object in Python, you often want to initialize its state (e.g., assign values to variables, open connections, validate input). This is done through a constructor.
Python provides a special method called __init__() that acts as the constructor for classes. There’s also a lower-level method, __new__(), for advanced object creation control.
In this guide, you’ll learn:
- What constructors are in Python
- The difference between
__init__()and__new__() - Default, parameterized, and multiple constructors
- Best practices and real-world examples
What Is a Constructor?
A constructor is a special method used to initialize an object’s attributes when it is created.
Python has two main constructors:
| Method | Purpose |
|---|---|
__init__() | Initializes the object after it’s created |
__new__() | Creates the object (low-level, rarely used) |
Using the __init__() Constructor
class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year
Creating an Object
c1 = Car("Tesla", 2024)
print(c1.brand) # Tesla
print(c1.year) # 2024
__init__() is automatically called after the object is created with Car(...).
Example – Default Constructor (No Arguments)
class Hello:
def __init__(self):
print("Hello from constructor!")
obj = Hello() # Output: Hello from constructor!
Parameterized Constructor
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
s1 = Student("Alice", "A")
print(s1.name) # Alice
Simulating Multiple Constructors (Overloading)
Python doesn’t support constructor overloading directly, but you can simulate it:
class Person:
def __init__(self, name=None):
if name:
self.name = name
else:
self.name = "Unknown"
p1 = Person("Bob")
p2 = Person()
print(p1.name) # Bob
print(p2.name) # Unknown
__new__() Constructor – For Advanced Use
__new__() is the actual constructor that allocates memory. Use it when you subclass immutable types like int, str, tuple.
class CustomInt(int):
def __new__(cls, value):
print("Inside __new__")
return super().__new__(cls, value)
obj = CustomInt(10)
__init__() runs after __new__().
Common Mistakes
| Mistake | Fix |
|---|---|
Forgetting self in __init__ | Always include self as the first argument |
| Not assigning parameters to attributes | Use self.attribute = value |
| Trying to overload like Java or C++ | Use default values or conditional logic |
Using __init__() to return values | Constructors should never return manually |
Best Practices
| Do This | Avoid This |
|---|---|
Use __init__() for object setup | Don’t return values from __init__() |
| Use default parameters for flexibility | Avoid multiple __init__() definitions |
Use __new__() for immutable types | Avoid using __new__() unnecessarily |
| Document your constructor clearly | Skip docstrings in public classes |
Summary – Recap & Next Steps
Constructors in Python let you automatically set up objects as they’re created. While __init__() is the go-to for initialization, __new__() offers lower-level control when needed.
Key Takeaways:
-
__init__()is Python’s primary constructor -
__new__()is used for object creation in special cases - Python does not support multiple constructors natively
- Use default arguments or conditionals to simulate overloading
Real-World Relevance:
Used in data models, API clients, ORM entities, and configuration classes.
FAQ – Python Constructors
Can Python classes have multiple constructors?
No direct support. But you can simulate using default arguments or @classmethod factory methods.
What is the difference between __init__() and __new__()?
__init__()initializes the object__new__()creates the object (used with immutable types)
Is __init__() mandatory?
No. If not defined, Python uses the default constructor.
Can I return a value from __init__()?
No. __init__() must return None. Use __new__() if you need to return a value during creation.
What happens if I forget self in __init__()?
You’ll get a TypeError. The first parameter of all instance methods must be self.
Share Now :
