Class level variables in Python

OKB (not okblacke) BrenBarn at
Thu Aug 28 02:35:12 CEST 2003

Brian Munroe wrote:

>>>> 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)

    	As I understand it, when you initialize the variables in __init__, 
they are instance variables; each rectangle has its own x.  When you 
set them up in the class definition as with z above, they are class 
variables; there is just one z in the whole rectangle class, not one 
for each object.

    	But, if you actually assign to r.x or r.z, it doesn't matter 
whether the property you're assigning to was originally defined as a 
class or instance variable.  Assigning to r.anyProp always creates an 
instance variable on the instance r.  Python does not check the 
object's superclasses to see if a class variable with the same name 

    	So, basically, when you assign to r.z, you're masking the class 
variable z by creating a new instance variable z on the instance r.  
You see that the class variable is unchanged by reading rectangle.z 
directly; it'll still be 2.

--OKB (not okblacke)
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
	--author unknown

More information about the Python-list mailing list