Static class members ?

Hans Nowak hnowak at cuci.nl
Tue Jul 31 10:28:40 EDT 2001


>===== Original Message From tripie at cpan.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





More information about the Python-list mailing list