static? + some stuff
eric.brunel at pragmadev.N0SP4M.com
Mon Nov 3 18:36:01 CET 2003
Daniel Schüle wrote:
> Hi all
> I have 2 questions
> is there a way do declare static variables in a class?
> I coded this logic in global variable foo_cnt
You just did:
> class foo:
> a = b = None
> c = 0
> my_id = 0
a, b, c and my_id *are* class attributes. They are actually inherited by
instances of foo, but declaring them this way makes them class attributes. You
should have done:
cnt = 0
def __init__(self, c=0):
foo.cnt += 1
self.a = self.b = None
self.c = c
self.my_id = foo.cnt
Attributes do not need to be *declared* at the top of the class in Python as in
C++ or Java: initializing them in the __init__ method is enough, and is probably
the safest way to handle them.
> 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?
Use the getattr built-in function:
tmp = cls()
attr = dir(tmp)
for i in attr:
print type(getattr(tmp, i))
You can see here that cnt is actually declared as an attribute of the *class*
foo, since you see it when you do a dir(cls), but not when you do a dir(tmp).
> thanks for your time
- Eric Brunel <eric dot brunel at pragmadev dot com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
More information about the Python-list