Question re class variable

Steven D'Aprano steve at pearwood.info
Tue Sep 29 08:06:13 EDT 2015


On Tue, 29 Sep 2015 09:17 pm, Anssi Saari wrote:

[...]
>> 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


This works because it doesn't assign to self.__instance_registry itself, it
assigns to an item within the existing self.__instance_registry. So the
registry object (a dict?) gets modified in place, not re-bound or shadowed
by an instance attribute of the same name.



-- 
Steven




More information about the Python-list mailing list