Python __new__ Explained With Examples

Hello geeks and welcome in today’s article we will cover Python new. Along with that, we will look at the definition and application of this method. We will do all that with the help of examples. As we know that python is a high-level programming language. With the help of it, we can also do object-oriented programming. In Python, there are several special methods know as magic methods or double underscore methods. They have been commonly used methods in operator overloading. It can be understood as a condition where the different operators have different implementations depending on their arguments.

The other thing that differentiates the magical method from the common method is that they have suffixes and prefixes of double underscore around them. Like __new__ , __add__, __init__ and etc. In this article, we will primarily focus on the magical method __new__. Further in this article, I will use new instead of __new__.

Python __new__ method and its syntax

In this section, we will try to understand what the new method really is. Along with that, we will also look at its syntax. To develop a complete understanding of this method.

In object-oriented programming whenever a class has instantiated the method new is called. The new method is called when an object is created and is a static method. A parameter cls. cls is required to pass through it. At the time of instantiation, the compiler itself takes care of it. Next, let us look at the syntax for this method.

Syntax

class class_name:
    def __new__(cls, *args, **kwargs):
        print()
        return super(class_name, cls).__new__(cls, *args, **kwargs)

This is the general syntax of the new method. Here we have used the super with our return statement. We use it because it returns a temporary object and allows us to access the methods of the base class. In the next let us look at some examples related to it.

Examples of Python __new__

class A(object): 
    def __new__(cls): 
         print("EXAMPLE-1") 
         return super(A, cls).__new__(cls) 
  
A()

Output:

EXAMPLE-1

Above we can see the very first example related to the new method. Here we have done nothing fancy and only motive was to execute syntax properly. Here we defined an object. Inside it, we have defined a new class. Then we have used a simple print and return super. At last, we just call the object.

import math
class A(object): 
    def __new__(cls): 
         a=input("enter the number")
         b=input("enter the number")
         c=int(a)+int(b)
         print(c)
         
         return super(A, cls).__new__(cls) 
  
A()

Output:

enter the number 7
enter the number 9
16

In this example, we have carried out the addition of 2 numbers. Here we have taken the input from the user. Rest we have just followed the concerned syntax. From the above 2 examples discussed, we can conclude that the new method is called automatically. As well as the return super statement should be used when dealing with magic methods.

Difference Between Python __new__ and __init__ magic methods

As so far in this article we have discussed the magic method new. The method __int__ is also automatically added when a class is instantiated. Here the difference between the 2 is that the init method is used to initialize the object. Also when both the methods are present in that case first the execution of the new method takes place. After which it is decided whether to use the init method or not. Let us see an example involving both the methods which will make things a lot clearer to us.

class A(object): 
    def __new__(cls): 
         print("New method") 
         return super(A, cls).__new__(cls) 
  
    def __init__(self): 
        print("Init method ") 
  
A() 

Output:

New method
Init method 

Above we can see a simple example involving both methods. From this, we can observe another thing which is that the new is called automatically. Whereas for the init it will be called every time at that instance.

Python __new__ with arguments

From python 2.6, the developers have ignored the extra arguments from object.__new__ method. This applies to all the python versions that are >2.6. Moreover, from python 3.2, it throws an error by passing arguments in python __new__.

See Also

Conclusion

In this article, we covered Python __new__. We covered a Magical method, which is called automatically whenever the class is instantiated. We also covered its definition and syntax. To understand the thing properly, we looked at a couple of examples. In the end, we also compared it with another function named init.

I hope this article was able to clear all doubts. But in case you have any unsolved queries feel free to write them below in the comment section. Done reading this, why not read about allclose next.

References

Python Documentation. Docs.Python.org.

Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Andrii
Andrii
3 years ago

If you started learning Python recently, find and read this article “The Inside Story on New-Style Classes”, it gives some real-world examples about the __new__ method.

Regarding the article, man you must have been in a hurry, please read what you’ve posted carefully; check PEP8 (class naming convention); inheritance from the object, and if you still want to inherit from object, at least don’t call super, call __new__ method directly: return object.__new__(cls)

Andreas Maier
Andreas Maier
1 year ago

On “From python 2.6, the developers have removed the extra arguments from object.__new__ method”:

That is not true. In the documentation of Python 2.7, 3.5 and higher, the object.__new__ method does have arbitrary parameters after the initial “cls” parameter: https://docs.python.org/3.10/reference/datamodel.html?highlight=__new__#object.__new__

Pratik Kinage
Admin
1 year ago
Reply to  Andreas Maier

Correct. Sorry for the incorrect phrasing of the statement. It was supposed to be ignored the extra arguments.