π 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 :