-1

Recently, I saw someone talking about a __new__ method and read an article about it. ( I always used __init__ before and never knew about __new__) The article explained that the __new__ method was called when an object is created and the __init__ method will be called to initialize the object.

What is the difference? What does it mean to initialize the object?

PetitJuju
  • 41
  • 3

3 Answers3

1

Both methods are being called. __new__ is called first and it return an instance of the class. This instance is passed to __init__ as self.

Read here for more.

balderman
  • 22,927
  • 7
  • 34
  • 52
0

In python EVERYTHING is an object so when you create a class, python create a class object. Assume this code:

class Example:
    def __init__(self) -> None:
        self.var = 0

python create a Example class object. In this object there are some methods such as __init__ and __new__. Then assume this peace of code:

obj = Example()

in runtime python is calling the __new__ method on Example class object and pass the istance (the __new__ result) to the __init__ method. And now you have your object.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Invictus
  • 426
  • 3
  • 13
0

As mentioned in link below and in my experience, we always use __init__ to define class constructor, but I rarely have seen that anyone uses __new__ .

Another point that is explained is that use __new__ if you're subclassing an immutable type like str, int, Unicode, or tuple. Immutable objects are Objects that wont change during program running.

https://dev.to/pila/constructors-in-python-init-vs-new-2f9j

Reza Akraminejad
  • 1,412
  • 3
  • 24
  • 38