Class vs instance variables?

Sandor Markon markon at rd.fujitec.co.jp
Wed May 12 21:54:56 EDT 1999


Sorry if this is a FAQ item but <insert lame excuse here>.
I am trying to figure out what data is shared btw instances
and what not. Could someone please explain this behavior:

class c:
    a=[]
    x=0
    def __init__(self,x):
        self.x=x
        self.a.append(x)

>>> c1=c(1)
>>> c1.x
1
>>> c1.a
[1]
>>>
>>> c2=c(2)
>>> c2.x
2
>>> c1.x
1
# so far, so good; c1 and c2 have their own instance variables x,
# and c1.x stays the same after creating c2. But:
>>> c1.a
[1, 2]
>>> c2.a
[1, 2]
# ??? Why is this list shared while the scalars are separate?
# How do I tell Python to make the list an instance var,
# or the scalar a class var?

-- 
Sandor Markon 
FUJITEC Co.Ltd. (G.O.C.), 28-10, Shoh 1-chome, Ibaraki, Osaka, JAPAN
Tel: 0726-22-8136  Fax: 0726-22-4472  email: markon at rd.fujitec.co.jp




More information about the Python-list mailing list