19
class Num:
   def __init__(self,num):
      self.n = num

I read that the __init__ method returns None.When I perform a=Num(5), Num(5) will call __init__ method of the class.But if __init__ returns None then a should reference nothing.But instead a is referencing the object of Num Class.How does it happen?So does __init__ return None or the object of the class?

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
tez
  • 4,990
  • 12
  • 47
  • 67

2 Answers2

38

__init__() returns None. It is __new__() that returns the new instance.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 6
    +1 (correct) It seems like your confusion stemmed from thinking that `__init__()` was the only method called when instantiating an object; `a=Num(5)` is not the same as `a=Num.__init__(5)` (note that the second one doesn't work). – Matthew Adams Aug 16 '12 at 05:54
  • 1
    +1 for __init__() is not the only method called.Thnx @MatthewAdams – tez Aug 16 '12 at 06:10
2

When doing a=Num(5), you do create the object and the newly created object is returned. But it is not as easy as you would directly call __init__ when creating the object. __init__ is called as part of the initiation process by some Python magic in the background. And basically the __new__ is part of that magic. However, there are only rare cases, where you want to fiddle with __new__. You should only do so, if you really know what you are doing and if there are really no easier ways to reach your goal.

schacki
  • 9,401
  • 5
  • 29
  • 32