Understanding behaviour of self with static variables
<p>I am confused with the behaviour of self when it comes to dealing with static variables in python.From what I understand is that static variables can be accessed by either using <code>classname.variablename</code> or <code>self.variablename</code>. However changing the value of that variable differs. I realized that if i change the static variable value by <code>classname.variablename=SomeValue</code> the instance variable reflects that value however if I change the value of static variable using <code>self.variablename=SomeValue</code> the static variable does not change when access like <code>classname.variablename</code> from what I understand is that when I assign a value like <code>self.variablename=SomeValue</code> then an instance variable is created. Can somebody please shed a little light on this behaviour.</p>

<p>Example 1:</p>

<pre><code>class bean:
    mycar="SomeCar"
    def test(self):
        bean.mycar = "yup"
        print(self.mycar) #prints yup
</code></pre>

<p>Example 2:</p>

<pre><code>class bean:
        mycar="SomeCar"
        def test(self):
            self.mycar = "pup"
            print(bean.mycar) #SomeCar
</code></pre>

<p>Both classes and instances can have attributes.</p>

<p>A class attribute is assigned to a class object. People sometimes call this a <em>"static variable"</em>.</p>

<p>An instance attribute is assigned to an instance (<em>"instance variable"</em>).</p>

<p>When an attribute of an object is <strong>read</strong>, a number of things happen (see <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">Descriptor HowTo Guide</a>), but the short version is:</p>

<ol>
<li>Try to read the attribute from the instance</li>
<li>If that fails, try to read it from the class</li>
</ol>

<p>When it is <strong>written</strong>, then there is no such mechanism. It is written where it is written ;)</p>

<p>See in example:</p>

<pre><code>class A(object):
    pass

a = A()

print A.value  # fails - there is no "value" attribute
print a.value  # fails - there is no "value" attribute

A.value = 7

print A.value  # prints 7
print a.value  # also prints 7 - there is no attribute on instance, but there is on class

a.value = 11

print A.value  # prints 7
print a.value  # prints 11 - now there is an attribute on the instance

a2 = A()

print a2.value  # prints 7 - this instance has no "value", but the class has
</code></pre>

<p><strong>self?</strong></p>

<p>BTW, the <code>self</code> argument (in the question) is an instance, just like <code>a</code> is here.</p>

python static-variables