In this blog, we will learn everything about the python __new__ method. We will understand the python __new__ method with various examples. so let’s get started.
What is python __new__ method
In Python, the new method is a special method that is called when a new instance of a class is created. The new method is responsible for allocating memory for the new object and returning the new object.
The __new__ method is used to control the creation of a new instance of a class. It is a static method that takes the class of which an instance was requested as its first argument
Syntax of python __new__ function
Below is the syntax for the new method in Python:
class MyClass: def __new__(cls, *args, **kwargs): # Custom code to create and return a new instance of the class instance = super().__new__(cls) return instance
The new method takes the following arguments:
- cls: the class being instantiated.
- *args: any positional arguments.
- **kwargs: any keyword arguments.
Example of python __new__ method
Below is a simple example of how to use the new method in python:
class TestClass: def __new__(cls, *args, **kwargs): print("Creating new instance") instance = super().__new__(cls) return instance # Create a new instance of MyClass obj = TestClass()
The new method of the TestClass class is called before the object is created. The new method prints a message indicating that a new instance is being created and then calls the new method of the parent class to allocate memory for the new object. Finally, it returns the newly created object.
python __new__ with arguments
We can also use the python new class with arguments. Below is an example of how you might it:
class TestClass: def __new__(cls, arg1, *args, **kwargs): print("Creating new instance") # Allocate memory for the new object instance = super().__new__(cls) # Set the value on the instance instance.value = arg1 # Return the new object return instance def __init__(self, *args, **kwargs): print(f"The value of instance is:{self.value}") # Create a new instance of MyClass obj = TestClass(10)
In the above example, the new method of the TestClass class is called before the object is created. The new method takes an additional argument arg1 and uses it to set the value attribute on the newly created instance.
After the object has been created, the init method of the TestClass class is called. This method prints the value of the value attribute on the instance.
The output of the above example looks like the below:
Creating new instance The value of instance is:10
python __new__ inheritance
In python, when a subclass inherits from a parent class, it can override the new method of the parent class to change the way instances of the subclass are created.
Below is an example of how new can be used in inheritance:
class TestParentClass: def __new__(cls, *args, **kwargs): print("Creating instance of TestParentClass") # Allocate memory for the new object instance = super().__new__(cls) # Return the new object return instance class TestChildClass(TestParentClass): def __new__(cls, *args, **kwargs): print("Creating instance of TestChildClass") # Allocate memory for the new object instance = super().__new__(cls) # Return the new object return instance # Create a instance of testChildClass obj = TestChildClass()
when creating an instance of TestChildClass
, the output will be:
Creating instance of TestChildClass Creating instance of TestParentClass
The TestChildClass is a subclass of TestParentClass and has overridden the new method of the parent class. When creating a new instance of TestChildClass, the new method of TestChildClass is called first, followed by the new method of TestParentClass
Python __new__ vs __init__
The new and init methods are two important functions in Python that are utilized during the process of creating a new object. They both play different purposes and are executed at different stages of object creation.
new is a static method that is executed first and its responsibility is to allocate memory for the new object. It returns a new instance of the class. By default, new calls the new method of the parent class to allocate memory for the new object. It can be customized by overwriting it.
init, on the other hand, is an instance method that is executed after a new has completed its task. Its purpose is to initialize the attributes of the newly created object. You can override init to define the default values for the attributes of your class and/or to accept and process arguments passed to the class constructor.
Below is the sample example that demonstrates the difference between new and init:
class TestClass: def __new__(cls, *args, **kwargs): print("Creating instance") # Allocate memory for the new object instance = super().__new__(cls) # Return the new object return instance def __init__(self, *args, **kwargs): print("Initializing instance") # Create a new instance of TestClass obj = TestClass()
In this example, the __new__
method is called first and is responsible for allocating memory for the new object. The __init__
method is then called and is responsible for initializing the attributes of the newly created instance.
It produces the below output