Class level variables in Python
cnetzer at sonic.net
Thu Aug 28 02:46:35 CEST 2003
On Wed, 2003-08-27 at 16:43, Brian Munroe wrote:
> I am just starting to learn the OO side of Python scripting, and I am
> a little confused on the following. Take the following example class:
> >>> class rectangle(object):
> z = 1
z is an attribute of the classes, and is shared across all instantiated
members of the class (ie. the objects constructed by calling
> def __init__(self):
> self.x = 2
This sets the x object in the specific object referred to by 'self' to
2. This object can set the value to something other than 2, outside of
__init__, and it won't be set in other rectangle objects
so, using your class:
>>> class rectangle(object):
... z = 1
... def __init__(self):
... self.x = 2
>>> rectangle.z = 5 # here I assign a new value to the class variable
>>> a.z # Both instances 'see' the new value
Note that the following will NOT work like you might expect!
>>> a.z = 7 # Assign to the z attribute of the a object
Ie. 'b' did NOT get 5. You have to assign to the class object. So,
each object can choose to "shadow" the class variables. If you need to
access the class variable, you can use the class name, or the __class__
Python is pretty simple and consistent. In the class definition, z = 1
assigns the 1 object to the name z in rectangle's namespace. The "def
__init__" *ALSO* assigns to the class's namespace, but this time it is a
function object which it calls '__init__'. All instantiations share
these attributes. Calling a member function is the same as accessing a
class attribute variable.
Also, since you assign the 'x' name to each instantiated object in the
initialization method, all the objects start with an 'x' attribute.
But, each object can change that 'x' name to something different, and
'x' is NOT part of the class namespace.
>>> a.x = 10
>>> b.x # b does not 'see' the change to a
>>> rectangle.x # classes are objects, separate from their creations
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: type object 'rectangle' has no attribute 'x'
There's more to be said, but this is a start. Here is a link:
Chad Netzer <cnetzer at sonic.net>
More information about the Python-list