<div class="gmail_quote">On 30 August 2012 15:11, Marco Nawijn <span dir="ltr"><<a href="mailto:nawijn@gmail.com" target="_blank">nawijn@gmail.com</a>></span> wrote:<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div class="HOEnZb"><div class="h5">
<br>
</div></div>Learned my lesson today. Don't assume you know something. Test it first ;). I have done quite some programming in Python, but did not know that class attributes are still local to the instances. It is also a little surprising I must say. I always considered them like static variables in C++ (not that I am an expert in C++).<br>
</blockquote><div><br></div><div>Class attributes are analogous to static variables in C++ provided you only ever assign to them as an attribute of the class.</div><div><br></div><div><div>>>> class A(object):</div>
<div>... static = 5</div><div>...</div><div>>>> a = A()</div><div>>>> a.static</div><div>5</div><div>>>> A.static</div><div>5</div><div>>>> b = A()</div><div>>>> b.static</div>
<div>5</div><div>>>> A.static = 10</div><div>>>> a.static</div><div>10</div><div>>>> b.static</div><div>10</div><div><div><br></div></div><div>An instance attribute with the same name as a class attribute hides the class attribute for that instance only.</div>
<div><br></div><div>>>> b.static = -1</div><div>>>> a.static</div><div>10</div><div>>>> b.static</div><div>-1</div></div><div><div><div>>>> del b.static</div><div>>>> b.static</div>
<div>10</div></div></div><div><br></div><div>This is analogous to having a local variable in a function that hides a module level variable with the same name:</div><div><br></div><div>x = 10</div><div><br></div><div>def f1():</div>
<div> x = 4</div><div> print(x)</div><div><br></div><div>def f2():</div><div> print(x)</div><div><br></div><div>f2() # 10</div><div>f1() # 4</div><div>f2() # still 10</div><div><br></div><div>If you want f1 to modify the value of x seen by f2 then you should explicitly declare x as global in f1.</div>
<div><br></div><div>Likewise if you want to modify an attribute for all instances of a class you should explicitly assign to the class attribute rather than an instance attribute.</div><div><br></div><div>Oscar</div></div>