static? + some stuff

KefX keflimarcusx at aol.comNOSPAM
Mon Nov 3 13:21:55 EST 2003


Some other people have replied already, but I don't think they've sufficiently
explained a possible gotcha (it's easy to spot for the experienced, but it can
catch newbies off-guard, and nobody likes chasing bugs for a couple hours):

>1)
>is there a way do declare static variables in a class?

In the sense of C++ and Java? Yup, sure is.

>>>class foo(object):
...  bar = 5  # Notice this is NOT set in __init__

This binds 'bar' to the class 'foo', and not any of its instances.

>>> baz = foo()
>>> baz.bar
5
>>> foo.bar = 6
>>> baz.bar
6

This suggests the value of foo.bar is shared throughout class instances: and it
is. But it's not bound to the class instances. In other words, if you print out
the __dict__ of baz, you won't find 'bar' in it anywhere (you'll get an empty
dictionary). It's in the __dict__ of foo, though, along with a couple other
things.

THIS MEANS YOU CANNOT CHANGE baz.bar, ONLY foo.bar.

>>> baz.bar = 7
>>> foo.bar
6

What happened? Well, assigning to baz.bar "overrided" the class variable: it
assumes that we want to bind a NEW variable named 'bar' to the class INSTANCE
rather than to the CLASS, and our 'static' behavior is smashed for this
particular instance. This is good if you want it, bad if you don't.

In other words, if you want a 'static' variable, for the expression "baz.bar is
foo.bar" to be True, baz must not have an item named bar in its dictionary.

Get it?

>2)
>is there a way to see the types of all data/function members of a class?

Do you mean the class, the class instance, or both? I hope my previous example
has shown there's a very important difference.

- Kef





More information about the Python-list mailing list