RE: Static class members ?
by Hans Nowak other posts by this author
Jul 31 2001 2:28PM messages near this date
RE: sleep command/function & searching the python docs
|
Arg decoding with a template?
> ===== Original Message From tripie@[...].org (Tomas Styblo) =====
> """
> Static class members ?
>
> Hello. I've found no way to properly create static data members in
> Python classes.
> By static members I mean data that are shared by all instances of a
> class.
> A textbook example of usage of static data is a counter of all
> instances of said class.
> I tried the following:
> """
>
> # Beginning of a module.
>
> class Parent:
>
> INSTANCES = 0
>
> def __init__():
> Parent.INSTANCES = Parent.INSTANCES + 1
>
> def get_INSTANCES():
> return Parent.INSTANCES
>
>
> """ That works OK. Problems come when I derive a new class from this
> Parent.
> Inherited methods in the derived class then reference the static
> data in
> Parent. This is not what I expect and need.
Maybe you want something like this?
#---begin code
class Parent:
counter = 0
def __init__(self):
self.__class__.counter += 1
def getcounter(self):
return self.__class__.counter
class Child(Parent):
counter = 0 # set a new counter for this class, so it won't
# use Parent's counter
# test it...
p1 = Parent()
p2 = Parent()
print p2.getcounter()
c1 = Child()
print c1.getcounter() # 1, not 3
#---end code
HTH,
--Hans Nowak
--
http://mail.python.org/mailman/listinfo/python-list
|