[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Why do we nned both - __init__() and __new__()

On Thu, 7 Sep 2017 08:57 pm, Andrej Viktorovich wrote:

> Hello
> For my understanding both - __init__() and __new__() works like constructors.
> And __new__() looks is closer to constructor. __init__() is more for variable
> initialization. Why I can't just initialize in __init__() ?

Because if your object is immutable, by the time __init__ is called, the object
is already frozen and you cannot initialise it.

Most of the time, just use __init__. You will soon realise when you need
__new__, and then you can worry about it. I've been using Python for two
decades, and I think I can count the number of times I've used __new__ on the
fingers of one hand.

Maybe two hands.

?Cheer up,? they said, ?things could be worse.? So I cheered up, and sure
enough, things got worse.