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>As Marcin answered, it is feasible, but it is not an advisable pattern.</p>

<p>Why would you like to do something like that? If you'd like instances of your class to have a settable property after instantiation, you shouldn't do it with a constructor. A simple solution for your proposal:</p>

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

<p>There would be alternative options depending on your intentions. Perhaps a default value?</p>

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

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

<p>I think the key here is: Try to be <strong>explicit</strong> instead of <strong>smart</strong>. It may look to you that the solution you're looking for is clever, but nothing beats <strong>clarity</strong> when you're coding.</p>

python class oop