static? + some stuff

John Roth newsgroups at jhrothjr.com
Mon Nov 3 13:02:01 EST 2003


"Daniel Schüle" <for_usenet2000 at yahoo.de> wrote in message
news:bo61tg$glg$1 at news.rz.uni-karlsruhe.de...
> Hi all
>
> I have 2 questions
> 1)
> is there a way do declare static variables in a class?
> I coded this logic in global variable foo_cnt

Yes, but it isn't as easy as a declaration. There are
basically two ways to do it. One (which works on
any version of Python) is to reference the class object
directly when setting the variable. For example:

class Foo:
    staticVar = None
    def setStaticVar(self, value):
        Foo.staticVar = value

The other is possible in release 2.2 and later:

class Foo:
    staticVar = None
    def setStaticVar(klas, value):
        klas.staticVar = value
    setStaticVar = classmethod(setStaticVar)

In the first example, setStaticVar is a normal
method that gets the instance as the first
parameter. In the second one, setStaticVar
gets the class object as the first parameter,
which is why I've named it klas instead of self.

> 2)
> is there a way to see the types of all data/function members of a class?
> dir(cls) returns a list of strings (of members) so it's logical that
> type(tmp.i) fails ...
> is it possible at all?

No. In general, instance variables are not represented in the
class object, so they won't show up if you only look at it.
If you want to look at the class object and a running instance
object, then you should be able to get all of the variables
and methods. Of course, if inheritance is involved, then you
would have to run the inheritance graph as well to find them.
You'd still have to write a bit of code (using getattr) to get
the actual objects and then make sense out of it, though.

John Roth
>
> thanks for your time
>
> --
> Daniel
>






More information about the Python-list mailing list