From: fredrik at pythonware.com (Fredrik Lundh)
Date: Thu, 13 May 1999 17:24:46 GMT
Subject: Class vs instance variables?
References: <373A30F0.7E61E813@rd.fujitec.co.jp>
Message-ID: <014e01be9d65$80944150$f29b12c2@pythonware.com>
Content-Length: 1155
X-UID: 1829                                                 

Sandor Markon <markon at rd.fujitec.co.jp> wrote:
> 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)

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

BOTH are shared.

it's just that you REPLACE the binding for the integer
(self.x = x creates a new instance binding for x, hiding
the one in the class), while you MODIFY the list in place.

no magic involved.

> # How do I tell Python to make the list an instance var,
> # or the scalar a class var?

to make class variables behave like class variables, you
need to access them through the class' namespace (use
c.a or c.x instead of self.a and self.x).

but you may wish to avoid class variables if you possibly
can. "global" (that is, module variables, not program globals)
variables are often easier to use.

</F>

PS. no chance you can teach your newsreader not to
mark your messages as "iso-2022-jp" when they only con-
tain plain ASCII?





