Class vs instance variables?

Alan Gauld alan.gauld at gssec.bt.co.uk
Thu May 13 07:46:40 EDT 1999


Sandor Markon wrote:
> I am trying to figure out what data is shared btw instances
> and what not. Could someone please explain this behavior:

I'll try but I'm relatively new to python too...

> class c:
>     a=[]

This is a class variable referencing a list
	
>     x=0

This is a class variable referencing an int

>     def __init__(self,x):
>         self.x=x

This creates a new instance variable which 'hides' the 
class variable and has value x.
Assignment in python creates a new reference.

>         self.a.append(x)

This *modifies* the existing reference(the class variable)
If you had done self.a = [1,2,3] you would have gotten 
an instance based list

> # ??? Why is this list shared while the scalars are separate?

Its nothing to do with the list/scalar asp[ects its to do 
with assignment versus modification.
- assignment creates a new instance variable.

At least thats hiw I underSTAND IT...

Alan g.

-- 
=================================================
This post represents the views of the author 
and does not necessarily accurately represent 
the views of BT.




More information about the Python-list mailing list