Question re class variable

Anssi Saari as at
Tue Sep 29 13:17:35 CEST 2015

Antoon Pardon <antoon.pardon at> writes:

> Op 29-09-15 om 11:27 schreef plewto at
>> I have a perplexing problem with Python 3 class variables. I wish to
>> generate an unique ID each time an instance of GameClass is
>> created. There are two versions of the __gen_id method with test run
>> results for each listed below the code.
> The problem is that in python you can't change a class variable through an instance. The moment you
> try, you create an instance attribute.

That much is clear but why does his other version of __gen_id() work
(after a fashion)? It doesn't increment the class variable but the
instances get an incremental id.

The function was like this:

    def __gen_id(self):
        ty = self.__class__.__name__
        id = ''
        while id in self.__instance_registry:
            id = '%s_%d' % (ty, self.__instance_counter)
            self.__instance_counter += 1
        self.__instance_registry[id] = self
        return id

Also, is there any problem with incrementing
GameObject.__instance_counter from __gen_id()? I guess not?

More information about the Python-list mailing list