+ 5
What is Use of __new__ in python?
https://code.sololearn.com/cTxgMi8O23h9/?ref=app Why is type of a None?
3 Antworten
+ 7
__new__ seems to be called automatically when you create an instance.
You redefined it to just print '__new__', it returns nothing.
In Python, whenever you return nothing from a function or method, you really return None.
I suppose, __new__would have to return self instead (just guessing here). EDIT: Nope, doesn't work that way.
Anyway, __new__ gets auto-called and returns None in the end, at the spot where you normally would want to have your instance.
Now I'm excited to hear any of you guys explain how and when and for what to use __new__. :-)
+ 6
__new__ should return a new instance of your class.
You should use it when you're subclassing an immutable type (like int or str) according to this page:
https://mail.python.org/pipermail/tutor/2008-April/061426.html
class Cls:
def __new__(cls, a):
self = super().__new__(cls)
self.a = a
return self
c = Cls('abc')
print(c, c.a)