+ 5
26th Jun 2019, 7:22 AM
Saksham Jain
Saksham Jain - avatar
3 odpowiedzi
+ 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__. :-)
26th Jun 2019, 7:58 AM
HonFu
HonFu - avatar
+ 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)
26th Jun 2019, 9:18 AM
Mert Yazıcı
Mert Yazıcı - avatar