osdir.com


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

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


Andrej Viktorovich <viktorovichandrej at gmail.com> writes:

> For my understanding both - __init__() and __new__() works like
> constructors.

Not true, they work quite differently and have very different jobs.

> And __new__() looks is closer to constructor. __init__() is more for
> variable initialization.

That's right.

The class's ?__new__? method ? note that it is a class method, it takes
the class as its first parameter ? is the constructor. It constructs a
new instance, and its return value is that instance.

The instance's ?__init__? method ? note that it is an instance method,
it takes the already-constructed instance as its first parameter ? is
the initialiser. It acts on the existing instance, setting it up for its
initial state, and its return value is None.

> Why I can't just initialize in __init__() ?

You can. You should.

What leads you to believe otherwise?

> class ExampleClass(object):
>     def __new__(cls,value):
>         print("creating new instance with val %s" % (value,) )
>         instance = super(ExampleClass,cls).__new__(cls)
>         return instance
>     def __init__(self, value):
>         print("Initialising instance... with val %s" % (value,))
>         self.payload = value

Yes, those look fine (but for new code you should be using Python 3,
which allows you to write ?instance = super().__new__()?).

-- 
 \         ?Our urge to trust our senses overpowers what our measuring |
  `\         devices tell us about the actual nature of reality.? ?Ann |
_o__)                                           Druyan, _Cosmos_, 2014 |
Ben Finney