Class static variables

Alex Martelli alex at magenta.com
Sat Jul 22 04:10:07 EDT 2000


<musingattheruins at my-deja.com> wrote in message
news:8lball$jrf$1 at nnrp1.deja.com...
> In article <8la2mp$n5v$1 at nnrp1.deja.com>,
>   Guillaume <forums at memoire.com> wrote:
> >
> > > you are attaching a per-object variable with b.a=2 try CA.a - i
> think
> > > you will find it is still 0.
> > > regards,
> > > bill
> >
> > Right, but what I want is a static class var defined in A.
>
> CA.a __is__ the static class var.  get it?  it's the same for all
> instances.

Yep, but what Guillaume clarified here, I think, is that it's
not the class-var itself that he's after, but, rather, altered
semantics for _assignment_ to it.  In Python,

    b.a = 2

binds or rebinds the a field in the OBJECT b -- doesn't matter
whether or not the CLASS of b also has an a field -- just as,
say, assigning to a inside a function binds or rebinds a in
the LOCAL namespace -- doesn't matter whether the GLOBAL one
has a as well.


This alteration is actually easier for the class case, as has
been pointed out, as long as, of course, __setattr__ knows
about it.  For the variable case you'd HAVE to say global in
each block that rebinds it (analogous to saying CA.a in an
explicit way for the class field case, I guess).


Alex






More information about the Python-list mailing list