🧱 Python Object-Oriented Programming (OOP)
Estimated reading: 3 minutes 27 views

πŸš€ 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:

MethodPurpose
__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 attributesUse self.attribute = value
Trying to overload like Java or C++Use default values or conditional logic
Using __init__() to return valuesConstructors should never return manually

πŸ“˜ Best Practices

βœ… Do This❌ Avoid This
Use __init__() for object setupDon’t return values from __init__()
Use default parameters for flexibilityAvoid multiple __init__() definitions
Use __new__() for immutable typesAvoid using __new__() unnecessarily
Document your constructor clearlySkip 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Constructors

Or Copy Link

CONTENTS
Scroll to Top