Python __init__ vs __new__
Last Updated :
30 Dec, 2024
In Python,
__init__
and __new__
are part of a group of special methods in Python commonly referred to as dunder methods or magic methods. The term "dunder" is short for "double underscore," reflecting the naming convention with double underscores at the beginning and end of the method names.
Python __new__
__new__
method in Python is a special method that's responsible for actually creating a new instance of a class. Think of it as the step where the object itself comes into existence, even before it gets initialized with specific values. It gets called automatically before the __init__
method, which is used to set up the object.
Let's understand this with an example :
Python
class CustomObject:
def __new__(cls, value):
# Create a new instance
instance = super().__new__(cls)
# Attach an attribute during creation
instance.value = value
return instance
# Creating objects
obj1 = CustomObject(10)
obj2 = CustomObject(20)
print(obj1.value)
print(obj2.value)
Explanation :
instance = super().__new__(cls)
: Calls the parent class’s __new__
to create an instance.instance.value = value
: Adds a custom attribute during creation.return instance
: Returns the newly created instance; object creation fails if not returned.
Python __init__
__init__
method in Python is a special method known as the initializer or constructor. It is called automatically when a new instance (object) of a class is created. Its primary purpose is to initialize the object's attributes (or set up its state) after the object has been created.
Let's understand this with an example :
Python
class SimpleObject:
def __init__(self, value):
# Initialize the instance
self.value = value
# Creating objects
obj1 = SimpleObject(10)
obj2 = SimpleObject(20)
print(obj1.value)
print(obj2.value)
Demonstration of __new__
and __init__
in Instance Creation
In Python, __new__ and __init__ are two special methods that play distinct roles in the object instantiation process:
Python
class MyClass:
def __new__(cls, *args, **kwargs):
print("GeeksforGeeks")
# Calling the parent class's __new__ method to create the instance
instance = super().__new__(cls)
return instance
def __init__(self, value):
# This method initializes the object after it's created
print(f"{value}")
self.value = value
# Create an instance of MyClass
obj = MyClass(10)
Explanation:
-
__new__
method is responsible for creating the instance. It’s called before __init__
and is where the object itself is actually created. - The
super().__new__(cls)
call creates the new instance, and then it’s returned so that Python can continue with the initialization. - After the instance is created by
__new__
, the __init__
method is called to initialize the object’s attributes.
Major Differences between __new__ and __init__
Aspect | __new__ | __init__ |
---|
Purpose | Responsible for creating a new instance of a class. It is called first when a new object is being created. | Responsible for initializing the instance after it has been created. It sets the initial state of the object by assigning values to instance variables. |
When They Are Called | Called before __init__ . It is used to control the creation of the object. | Called after __new__ and is used to initialize the newly created object |
Return Value | Must return the newly created instance (object), which is then passed to __init__ . | Does not return anything. Its role is only to initialize the object after it's created. |
Common Usage | Typically rarely overridden. It is most commonly used when dealing with immutable objects. | Frequently overridden to initialize attributes of an object. It is used in most classes to set up the state of the object. |
Inheritance Behavior | It is called by the class itself or its metaclass. It must return an instance of the class, and in the case of inheritance, it will call super().__new__(cls) to create an instance. | It is called on the instance of the object, and in the case of inheritance, it is called for each subclass instance. |
Similar Reads
__init__ in Python Prerequisites - Python Class and Objects, Self__init__ method in Python is used to initialize objects of a class. It is also called a constructor. It is like a default constructor in C++ and Java. Constructors are used to initialize the objectâs state.The task of constructors is to initialize (assig
5 min read
Inheritance in Python Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read
Private Variables in Python Prerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Name mangling in Python In name mangling process any identifier with two leading underscore and one trailing underscore is textually replaced with _classname__identifier where classname is the name of the current class. It means that any identifier of the form __geek (at least two leading underscores or at most one trailin
3 min read
Environment Variables in Python Environment variables are key-value pairs that live in our system's environment. Python reads some of these variables at startup to determine how to behave, for example, where to look for modules or whether to enter interactive mode.If thereâs ever a conflict between an environment variable and a co
3 min read
Instance method in Python A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
2 min read