Static Data?

Peter Otten __peter__ at web.de
Sat Apr 10 11:24:41 EDT 2004


Stevie_mac wrote:

> I need to have a static class data member like c (see semi pseudo-like
> code below). How can I achieve this?

class Object:
    # Python already has a builtin object class;
    # use uppercase Object to avoid nameclash
    _ID = 1
    def __init__(self):
        self.ID = Object._ID
        Object._ID += 1

# An alternative implementation
# import itertools
# class Object:
#     IDGen = itertools.count(1)
#     def __init__(self):
#         self.ID = self.IDGen.next() # successive calls yield 1, 2, 3, ...

class Group(dict):
    # you could make this more dict-like
    def addObject(self, obj):
        self[obj.ID] = obj
    def getObject(self, iWhich):
        return self[iWhich]

g = Group()

o1 = Object()
o2 = Object()
o3 = Object()

g.addObject(o2)
g.addObject(o3)
g.addObject(o1)

print g.getObject(1).ID
print g.getObject(2).ID
print g.getObject(3).ID

The above works, but I've got a hunch that you are on the wrong track here.
Most likely you should pass o1, o2, ... around instead of the IDs.

Peter




More information about the Python-list mailing list