Skip to content Skip to sidebar Skip to footer

Why Do We Need To Use __new__() When Extending A Immutable Class In Python?

I am reading the book Mastering Object-Oriented Python. In the part of book where it talks about the __new__ method and immutable objects, it says something like the __new__() meth

Solution 1:

If you do MyClass(1), then 1 is indeed passed as an argument to __init__. But __new__ is called before __init__, so 1 is first passed as an argument to __new__. The error you are seeing is because you didn't override __new__, so the inherited float.__new__ is being called, and it doesn't accept your extra argument. It never gets a chance to even try calling __init__, because it fails when trying to call __new__.

This is explained in the documentation. As clearly stated there, the arguments you pass when instiating a class (e.g., the 1 in MyClass(1)) are passed to both__new__and__init__, in that order.

Solution 2:

By the time the __init__ method runs, the object already exists. Since the object is immutable, its value can't be changed in __init__.

Post a Comment for "Why Do We Need To Use __new__() When Extending A Immutable Class In Python?"