class object's attribute is also the instance's attribute?

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Aug 30 19:58:14 CEST 2012


On 30 August 2012 15:11, Marco Nawijn <nawijn at gmail.com> wrote:
>
>
> 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++).
>

Class attributes are analogous to static variables in C++ provided you only
ever assign to them as an attribute of the class.

>>> class A(object):
...   static = 5
...
>>> a = A()
>>> a.static
5
>>> A.static
5
>>> b = A()
>>> b.static
5
>>> A.static = 10
>>> a.static
10
>>> b.static
10

An instance attribute with the same name as a class attribute hides the
class attribute for that instance only.

>>> b.static = -1
>>> a.static
10
>>> b.static
-1
>>> del b.static
>>> b.static
10

This is analogous to having a local variable in a function that hides a
module level variable with the same name:

x = 10

def f1():
    x = 4
    print(x)

def f2():
    print(x)

f2()  # 10
f1()  # 4
f2()  # still 10

If you want f1 to modify the value of x seen by f2 then you should
explicitly declare x as global in f1.

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.

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120830/a16c4d8d/attachment.html>


More information about the Python-list mailing list