class variable won't icrement!

Gumuz gumuz at looze.net
Thu Sep 12 04:54:40 EDT 2002


Hello everyone,

I have something very strange and i can not understand it. probably, it's
not _that_ strange : )

I have this simple class which registers itself on a class variable in the
following code:

----------------------------------------------------------------------------
------
class test:
    dict = {}
    id = 1
    def __init__(self, name):
        self.dict[name] = self
        self.id = self.id + 1

    def show(self):
        print "class variable dict element count: ", str(len(self.dict))
        print "class variable id: ", self.id
----------------------------------------------------------------------------
--------

now, look at the following:

>>> john = test("john")
>>> frank = test("frank")
>>> bill = test("bill")
>>> bill.show()
class variable dict element count:  3
class variable id:  2
>>> frank.show()
class variable dict element count:  3
class variable id:  2

The dict variable acts fine, maintaining it's content throughout every
instance of the class.
The id variable however, seems to be only incremented within the instance.
In the end this variable should've been 4.

Could someone explain this to me? Is there something about class variables
whta i should know?

many thanx,
Guyon







More information about the Python-list mailing list