Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

9. Separate __new__ and __init__: Two Different Python Constructors

Sumit Rawal answered on May 13, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers


9. Separate __new__ and __init__: Two Different Python Constructors

0

When it comes to constructors of Python classes, all of us know the __init__ method, but fewer developers know the __new__ method.

The difference between these two methods is simple:

The __new__() method creates a new instance.

The __init__() method initialises that instance.

The __new__ method is a special method that is called before the __init__ method. It is responsible for creating the object and returning it. The __new__ method is a static method, which means that it is called on the class, rather than on an instance of the class.

In general, we don’t need to override the __new__ method. Because in most cases, the default implementation of it is sufficient.

If you need some more precise control of your classes, overriding the __new__ method is also a good choice.

For example, if you would like to apply the singleton pattern to a Python class, you may implement it as follows:

Popularity 1/10 Helpfulness 1/10 Language python
Source: Grepper
Tags: python
Link to this answer
Share Copy Link
Contributed on May 13 2023
Sumit Rawal
0 Answers  Avg Quality 2/10


X

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
X
Grepper Account Login Required

Oops, You will need to install Grepper and log-in to perform this action.