python recursion class variable
<p>Let me rewrite my question so that it is clearer. I encountered a issue on LeetCode problem: validate binary search tree. </p>

<p>My first solution looks something like this:</p>

<pre><code>class Solution(object):
    def recursion(self, input, var_x, ans):
        #update var_x
        #update ans
        self.recursion(input, var_x, ans)

    def mySolution(self, input):
        ans = []
        var_x = 0
        self.recursion(input, var_x, ans)
        return ans
</code></pre>

<p>This solution fails to pass the test. But after I made a simple change, it passes:</p>

<pre><code>class Solution(object):
    def recursion(self, input, ans):
        #update self.var_x
        #update ans
        self.recursion(input, ans)

    def mySolution(self, input):
        ans = []
        self.var_x = 0
        self.recursion(input, ans)
        return ans
</code></pre>

<p>What is the difference that declare var_x versus self.var_x? I think these two has the same effect in this problem, but one passes the test the other doesn't?</p>

<p>The semantic difference is simple: <strong>var_x</strong> is merely a local variable, one per call instance.  <strong>self.var_x</strong> is an attribute of the object, one per class instance.</p>

<p>If you need the value only within the one call instance, use <strong>var_x</strong> and don't bother the objects with storing the transient value.  If you need it as a long-term object property (attribute), then use <strong>self.var_x</strong>.</p>

python recursion binary-search-tree inorder