Class vs instance variables?
Fredrik Lundh
fredrik at pythonware.com
Thu May 13 13:24:46 EDT 1999
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?
More information about the Python-list
mailing list