Assign a class to itself in python
<p>I just want to ask if I can assign an instance of a class to itself in a method.</p>

<p>For example, is the following valid python code?</p>

<pre><code>class O(object):
  def __init__(self,value):
    self.value = value
  def do_something(self):
    self = O(1)
</code></pre>

<p>Does this lead to any unexpected behaviour?</p>

<p>Obviously, the code can be run. But when I do</p>

<pre><code>A = O(2)
A.do_something()
A.value 
</code></pre>

<p>the output is <code>2</code>, when I expect it to be <code>1</code>.</p>

<p><code>self</code> is <em>just another local variable</em>. You can assign something else to it just like you can assign something to any variable. To begin with, <code>self</code> points to the same object <code>A</code> points to in your example.</p>

<p>When you then execute <code>self = O(1)</code>, that statement <em>rebinds</em> the name <code>self</code>. It was previously referencing an instance of <code>O()</code>, and now you point it to <em>another, different</em> instance of <code>O()</code>. Those two objects are otherwise independent, doing this doesn't make anything else happen. <code>A</code> still references the first instance, <code>self</code> now references a different one.</p>

<p>So assigning <code>O(2)</code> to <code>self</code> doesn't do anything to the previous object that <code>self</code> pointed to. It certainly won't alter the value of the <code>value</code> attribute of that previous object. <code>A</code> still points to the first instance, where the <code>value</code> attribute is pointing to the integer <code>2</code>.</p>

<p>You may want to read this article on Python names, by Ned Batchelder: <a href="http://nedbatchelder.com/text/names.html" rel="nofollow"><em>Facts and myths about Python names and values</em></a>, which lays out what happens when you assign something to a Python variable. <code>self</code> is nothing special here.</p>

python class oop