static? + some stuff
Eric Brunel
eric.brunel at pragmadev.N0SP4M.com
Mon Nov 3 12:36:01 EST 2003
Daniel Schüle wrote:
> 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
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:
class foo:
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.
> 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?
Use the getattr built-in function:
def print_type_of_all_attr_of_class(cls):
tmp = cls()
attr = dir(tmp)
print attr
for i in attr:
print type(getattr(tmp, i))
print_type_of_all_attr_of_class(foo)
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
>
> --
> Daniel
HTH
--
- 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
mailing list