variable scope of class objects

Nagy László Zsolt gandalf at shopzeus.com
Tue Oct 20 02:38:04 EDT 2015


> These two statements make me think you come from C++ or something
> similar.
>
> In Python you can declare variables at class level, but this
> declaration must NOT be interpreted in the same manner of a similar
> declaration in C++: they remain at the abstract level of a class, and
> they have nothing to do with an instance of a class (in fact, to be
> correctly invoked, they must be preceeded by the class name).
When you say "they have nothing to do", it is almost true but not 100%.

When accessing attributes of an instance, Python first searches in the
namespace of the instance. When not found, it searches in the namespace
of its class.

So for example:

>>>
>>> class A(object):
...     a = ["value 1"]
...     def set_a(self):
...         # This will bind the value  to the name "a" in the namespace
of the instance (!!!), not the class
...         self.a = ["value 3"]
...
>>> a = A()
>>> b = A()
>>> print A.a # ["value 1"]
['value 1']
>>> print a.a  # ["value 1"]
['value 1']
>>> print b.a  # ["value 1"]
['value 1']
>>> A.a.append("value 2")
>>> print A.a # ["value 1","value 2"]
['value 1', 'value 2']
>>> print a.a  # ["value 1","value 2"]
['value 1', 'value 2']
>>> print b.a  # ["value 1","value 2"]
['value 1', 'value 2']
>>> a.set_a()
>>> print a.a  # ["value 3"]
['value 3']
>>> print A.a # ["value 1","value 2"]
['value 1', 'value 2']
>>> print b.a # ["value 1","value 2"]
['value 1', 'value 2']
>>> print A.a is b.a # True
True
>>> print a.a is b.a # False
False
>>> b.a.append("value 4")
>>> A.a
['value 1', 'value 2', 'value 4']
>>> del a.a
>>> a.a
['value 1', 'value 2', 'value 4']
>>>

Some objects are designed this way: the attribute with the same name can
be bound to an object stored at class level or at instance level,
depending on how the object was created or used. In other words: when
you access an attrbute through an object, you can very well reach a
class attribute instead of an object attribute; and this behaviour can
be different for different instances of the same class. Just look at the
last attribute deletion - by deleting an attribute of an instance,
further attribute access will hit the class level object. The same
behaviour is unthinkable with C++.







More information about the Python-list mailing list