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.
Hi, I'm Swastik Baranwal, a software developer from New Delhi, India passionate about open-source contribution, Gopher, Pythoneer, Compiler Design and DevOps.
Hi, I'm Swastik Baranwal, a software developer from New Delhi, India passionate about open-source contribution, Gopher, Pythoneer, Compiler Design and DevOps.
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:Also, it can be used to create a singleton:
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, notExample.__init__
, as the returned object is not of typeExample
butint
. In the second example you have to be careful in__init__
, because it is called every time you “instantiate” the object (ie. you doa = Example()
), even though they return the same object.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.
Sure, go ahead and use it! I’m glad i could help.
I just don't want to mislead people especially beginners.