DEV Community

Discussion on: Python: __init__() is not the only constructor

Collapse
 
gergelypolonkai profile image
Gergely Polonkai

In all honesty, this post confused me a lot. And my $job is Python for about 6 years now.

After reading it several times, i finally see your point, but the whole thing should be edited, if not rewritten, to make it easier to understand, especially for beginners.

The most important thing is that __new__ controls object creation. That means, in an extreme case, you can return a completely different type of object at the end:

class Example:
    def __new__(cls):
        return 3

type(Example())
# output: int

Also, it can be used to create a singleton:

_singleton = None

class Example:
    def __new__(cls):
        global _singleton

        if _singleton is None:
            _singleton = super(Example, cls).__new__(cls)

        return _singleton

a = Example()
b = Example()
a is b
# output: True

After the object is created, the object’s __init__ method is called. This one is especially tricky; for example, in my first example, int.__init__ will be called, not Example.__init__, as the returned object is not of type Example but int. In the second example you have to be careful in __init__, because it is called every time you “instantiate” the object (ie. you do a = Example()), even though they return the same object.

Collapse
 
delta456 profile image
Swastik Baranwal

Yeah I have missed that and I will probably re-write this post again. Thanks for enlightening that for me!

Also can I use your code which you have given to explain? Would be awesome if you aloowed.

Collapse
 
gergelypolonkai profile image
Gergely Polonkai

Sure, go ahead and use it! I’m glad i could help.

Thread Thread
 
delta456 profile image
Swastik Baranwal

I just don't want to mislead people especially beginners.