Question re class variable

Antoon Pardon antoon.pardon at rece.vub.ac.be
Tue Sep 29 08:02:34 EDT 2015


Op 29-09-15 om 13:17 schreef Anssi Saari:
> Antoon Pardon <antoon.pardon at rece.vub.ac.be> writes:
>
>> Op 29-09-15 om 11:27 schreef plewto at gmail.com:
>>> 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

Because you check against the class variable __instance_registry. That variable
isn't rebound, it is mutated, so it remains a class variable and can thus be used
to check which id's are already in use. So you increment your counter until the
corresponding id is not in the __instance_registry.

-- 
Antoon Pardon. 




More information about the Python-list mailing list