Static class members ?

Tomas Styblo tripie at cpan.org
Tue Jul 31 09:28:39 EDT 2001


"""
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.

    The second way I tried was:
"""

# Beginning of a module.

INSTANCES = 0

class Parent:

    def __init__():
        INSTANCES = INSTANCES + 1

    def get_INSTANCES():
        return INSTANCES


""" This also isn't an optimal solution, because the derived class
doesn't pass
    the "empty subclass" inheritance test. I have to manually add the
"static"
    variables to its module to make it work.

    Anyone please know what the optimal solution of this problem is ?

    Tomas Styblo
    tripie at cpan.org
"""



More information about the Python-list mailing list