Class level variables in Python

Terry Reedy tjreedy at udel.edu
Wed Aug 27 20:52:14 EDT 2003


"Brian Munroe" <bmunroe at tribador.nu> wrote in message
news:c16d085c.0308271543.3dfc581e at posting.google.com...
> 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
> def __init__(self):
> self.x = 2
>
> >>> r = rectangle()
> >>> print r.z
> 1
> >>> print r.x
> 2
> >>> r.z = 16
> >>> print r.z
> 16
> >>> r.x = 17
> >>> print r.x
> 17
> >>>
>
> I was wondering if someone could explain if there is any difference
> between initalizing your object attributes up in the __init__
> constructor or setting them up as (I am guessing at the name here)
> object level variables (like z)

Everything set at 'top' level under the class statement is a class
attribute.  Ditto for anything set outside the class statement as
someclass.attribute.  This include instance methods, which are common
to all instances and therefore *attributes* of the class.

Everything set within instance methods as self.attribute or outside as
someinstance.attribute are instance attributes private to that
instance.  Just as a function can have a private local variable with
the same name as a 'public' global variable, an instance can have an
attribute of the same name as an attribute of its class.  Just as
function locals 'mask' the global of the same name, instance 'locals'
usually* mask the class attribute of the same name.

In your example above, you start with class attribute z and later add
an r instance attribute of same name (but different value).  First you
see one, then the other.

(* I believe the masking exception alluded to above has something to
do with special methods, descriptors, and classes derived from
builtins, but I do not know the current rule will enough to even quote
it.  But beginners usually need not worry about it.)

Terry J. Reedy






More information about the Python-list mailing list