Static Data?

John Roth newsgroups at jhrothjr.com
Sat Apr 10 15:03:19 EDT 2004


"Stevie_mac" <no.email at please.com> wrote in message
news:2FTdc.56817$Id.5813 at news-binary.blueyonder.co.uk...
> I need to have a static class data member like c (see semi pseudo-like
code below). How can I achieve this?

You want an updatable class member. There are two ways
of doing this.

1) Reference the class directly:

class MyObject:
    _id = 0

    def __init__(self):
        MyObject._id += 1
        self.ID = _id

2) use a class method:

class MyObject(object):
    _id = 0

    def nextID(klas):
        klas._id += 1
        return klas._id
    nextID = classmethod(nextID)

    def __init__(self):
        self.ID = self.nextID()

Method 1 works in all releases of Python. Method 2
requires release 2.2 or later.

HTH

John Roth





More information about the Python-list mailing list