Constructors in Python (init vs __new__)

WHAT TO KNOW - Aug 18 - - Dev Community

<!DOCTYPE html>



Constructors in Python: init vs new

<br> body {<br> font-family: Arial, sans-serif;<br> margin: 0;<br> padding: 20px;<br> }</p> <div class="highlight"><pre class="highlight plaintext"><code>h1, h2, h3 { color: #333; } code { background-color: #f2f2f2; padding: 5px; border-radius: 3px; font-family: Consolas, monospace; } pre { background-color: #f2f2f2; padding: 10px; border-radius: 3px; overflow-x: auto; } img { max-width: 100%; height: auto; } </code></pre></div> <p>



Constructors in Python: init vs new



In Python, constructors are special methods that are invoked when an object is created. They play a crucial role in setting up the initial state of an object. The two primary constructors in Python are

init

and

new

. While both are involved in object creation, they have distinct roles and functionalities.



Introduction to Constructors in Python



Constructors are essential for object-oriented programming as they allow us to initialize objects with specific values and properties. The constructor method is called automatically when a new instance of a class is created. It provides a framework for defining how an object should be set up upon its creation.



Overview of

init

and

new

Methods




init

: The Initialization Method



The

init

method is responsible for initializing the attributes of an object. It is called after the object has been created by

new

. The first argument of

init

is always

self

, which refers to the newly created object. The remaining arguments are the parameters passed to the class constructor.



class Dog:
def init(self, name, breed):
self.name = name
self.breed = breed


In this example, the

init

method assigns the

name

and

breed

values passed to the constructor to the corresponding attributes of the

Dog

object.




new

: The Object Creation Method



The

new

method is responsible for creating the object itself. It is the very first method invoked when a class is instantiated. Its role is to allocate memory for the object and return the newly created object. It typically accepts the class as its first argument and any other arguments required for creating the object.



class MyObject:
def new(cls, *args, **kwargs):
instance = super().new(cls, *args, **kwargs)
return instance


In this example,

new

calls the

super().new

method, which delegates the actual object creation to the parent class (

object

in this case). It then returns the newly created instance.



Key Differences Between

init

and

new


| Feature |

init

|

new

|
|---|---|---|
| Purpose | Initialize object attributes | Create the object |
| Order of Execution | Called after

new

| Called before

init

|
| Arguments |

self

(object instance) and other constructor arguments | Class and other arguments required for object creation |
| Return Value | None | Newly created object |


Examples Demonstrating the Use of Both Methods



Example 1: A Simple Class



class Person:
def new(cls, name, age):
print("Creating new Person object...")
instance = super().new(cls)
return instance

def init(self, name, age):
print("Initializing Person object...")
self.name = name
self.age = age

person1 = Person("John", 30)
print(person1.name) # Output: John
print(person1.age) # Output: 30



In this example,

new

is used to create the

Person

object, and

init

initializes the

name

and

age

attributes.



Example 2: Controlling Object Creation



class Singleton:
instance = None

def new(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super().new(cls, *args, **kwargs)
return cls.instance

def init(self, data):
self.data = data

s1 = Singleton("Hello")
s2 = Singleton("World")

print(s1 is s2) # Output: True
print(s1.data) # Output: Hello
print(s2.data) # Output: Hello



This example demonstrates how

new

can be used to implement a Singleton pattern, ensuring that only one instance of the class is ever created. The

new

method checks if an instance already exists and returns the existing instance if so.



Example 3: Custom Object Creation



class CustomObject:
def new(cls, *args, **kwargs):
print("Creating custom object...")
return super().new(cls, *args, **kwargs)

def init(self, data):
print("Initializing custom object...")
self.data = data

def str(self):
return f"CustomObject: {self.data}"

obj1 = CustomObject("Data 1")
obj2 = CustomObject("Data 2")

print(obj1) # Output: CustomObject: Data 1
print(obj2) # Output: CustomObject: Data 2



Here,

new

is used to customize the object creation process, printing a message before the actual object is created.



Best Practices for Using

init

and

new

  • Use init for attribute initialization: This is the standard way to set up the initial state of an object.
    • Use new sparingly: Only override new when you need to control the object creation process, such as for Singleton patterns, metaclasses, or custom object creation.
    • Always call super().new(cls) in new : This ensures that the object is properly created by the parent class.
    • Avoid complex logic in new : Keep new focused on object creation and delegate initialization logic to init .

      Conclusion: When to Use init vs new

      In most cases, you should rely on init for initializing object attributes. new is primarily used for special cases, such as:

  • Singleton pattern: To ensure that only one instance of a class exists.
    • Metaclasses: To customize class creation.
    • Custom object creation: To control the object creation process in specific scenarios.

      By understanding the roles of init and new , you can write more robust and efficient Python code.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player