title: __new__ and __init__ in Python
body: <p>I am learning Python and so far I can tell the things below about <code>__new__</code> and <code>__init__</code>:</p>
  
  <ol>
  <li><code>__new__</code> is for object creation</li>
  <li><code>__init__</code> is for object initialization</li>
  <li><code>__new__</code> is invoked before <code>__init__</code> as <code>__new__</code> returns a new instance and <code>__init__</code> invoked afterwards to initialize inner state.</li>
  <li><code>__new__</code> is good for immutable object as they cannot be changed once they are assigned. So we can return new instance which has new state.</li>
  <li>We can use <code>__new__</code> and <code>__init__</code> for both mutable object as its inner state can be changed.</li>
  </ol>
  
  <p>But I have another questions now. </p>
  
  <ol>
  <li>When I create a new instance such as <code>a = MyClass("hello","world")</code>, how these arguments are passed? I mean how I should structure the class using <code>__init__</code> and <code>__new__</code> as they are different and both accepts arbitrary arguments besides default first argument.</li>
  <li><code>self</code> keyword is in terms of name can be changed to something else? But I am wondering <code>cls</code> is in terms of name is subject to change to something else as it is just a parameter name?</li>
  </ol>
  
  <p>I made a little experiments as such below:</p>
  
  <pre><code>&gt;&gt;&gt; class MyClass(tuple):
      def __new__(tuple):
          return [1,2,3]
  </code></pre>
  
  <p>and I did below:</p>
  
  <pre><code>&gt;&gt;&gt; a = MyClass()
  &gt;&gt;&gt; a
  [1, 2, 3]
  </code></pre>
  
  <p>Albeit I said I want to return <code>tuple</code>, this code works fine and returned me <code>[1,2,3]</code>. I knew we were passing the first parameters as the type we wanted to receive once the <code>__new__</code> function is invoked. We are talking about <code>New</code> function right? I don't know other languages return type other than bound type?</p>
  
  <p>And I did anther things as well:</p>
  
  <pre><code>&gt;&gt;&gt; issubclass(MyClass,list)
  False
  &gt;&gt;&gt; issubclass(MyClass,tuple)
  True
  &gt;&gt;&gt; isinstance(a,MyClass)
  False
  &gt;&gt;&gt; isinstance(a,tuple)
  False
  &gt;&gt;&gt; isinstance(a,list)
  True
  </code></pre>
  
  <p>I didn't do more experiment because the further wasn't bright and I decided to stop there and decided to ask StackOverflow.</p>
  
  <p>The SO posts I read:</p>
  
  <ol>
  <li><a href="https://stackoverflow.com/questions/1164309/python-object-creation">Python object creation</a></li>
  <li><a href="https://stackoverflow.com/questions/674304/pythons-use-of-new-and-init">Python&#39;s use of __new__ and __init__?</a></li>
  </ol>