[Tutor] When to use __new__ vs. __init__ ?

Alan Gauld alan.gauld at yahoo.co.uk
Wed Apr 29 12:07:28 EDT 2020


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




More information about the Tutor mailing list