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.
Post a Comment for "Why Do We Need To Use __new__() When Extending A Immutable Class In Python?"