[Tutor] When to use __new__ vs. __init__ ?

wesley chun wescpy at gmail.com
Wed Apr 29 19:52:33 EDT 2020


I concur with both Mats' and Alan's responses, and add that more
explicitly, __new__() is really only used for subclassing existing (user or
built-in) *immutable* types, not all Python built-in types. (If you
subclass dict or list, you don't need __new__() ). (Although, subclassing
mutable types have their own issues
<https://treyhunner.com/2019/04/why-you-shouldnt-inherit-from-list-and-dict-in-python/>
.)

With traditional object-oriented languages, you have constructors (and
destructors) whose job it is to allocate/create (and deallocate/destroy)
objects. Python works differently in that the *Python interpreter* manages
your memory, i.e., it does the creation (and destruction) of regular
objects. That's why __init__() is named as an "initializer" more than a
constructor.

For immutables, it's different because you need to be able to specify what
you want in such an object *before* it's created, so __new__() serves that
purpose... to specify its setup and then let Python create that object. For
normal/mutable objects, Python creates the object first, then lets you
initialize/customize it with __init__() before it's returned to be used by
your application. You'd only pick one (normal/mutable/__init__ or immutable/
__new__) and never both.

Cheers,
--Wesley

On Wed, Apr 29, 2020 at 9:07 AM Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 29/04/2020 12:46, Abhishek M wrote:
>
> As ats said you use both of them every time you create an instance of a
> class.
>
> But in practice you normally override __init__() to initialize
> any class attributes that you have introduced. It is much less common to
> override __new__().
>
> The main use case for overrriding __new__() is when you are subclassing
> one of the built-in types such as int or list. An example would be
>
> class Integer(int):
>    # do some fancy integer type things...
>    def __new__(cls,n):
>       # whatever...
>       return super().__new__(cls, n)
>
> Remember that the first parameter in __init__(), traditionally spelled
> self, represents the new instance of the class and returns None.
> Whereas, the first parameter of __new__(), traditionally spelled cls,
> represents the class itself and it return an instance of the class.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos


-- 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"A computer never does what you want... only what you tell it."
    +wesley chun : wescpy at gmail : @wescpy
    Python training & consulting : http://CyberwebConsulting.com
    "Core Python" books : http://CorePython.com
    Python blog: http://wescpy.blogspot.com


More information about the Tutor mailing list