Question re class variable

plewto at gmail.com plewto at gmail.com
Tue Sep 29 05:27:23 EDT 2015


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. 

Originally I used the version which is now commented out. When a new instance was created it created an ID by appending the value of __instance_counter to the class name, it then checked the contents of of __instatance_registrty to see if this ID was already in use. If so it incremented the counter until it found an unused ID. This version works exactly as I expected.

Later I decided to get rid of __instance_registry and rely solely on the restricted access to __instance_counter and the fact that it is monotonically increasing to generate IDs. I wrote the second, simpler version of __gen_id to that end, but it doesn't work!  No doubt I'm overlooking something very simple here but I'm not seeing it. 

Any help appreciated. 


class GameObject:

    # __instance_registry = {"":None}
    __instance_counter = 0
    
    def __init__(self, name):
        self.__name = str(name)
        self.__id = self.__gen_id()

    # 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

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

    def __str__(self):
        return "name = '%s'   id = '%s'" % (self.__name, self.__id)  
    

go1 = GameObject("GO1")
go2 = GameObject("GO2")
go3 = GameObject("GO3")
print(go1)
print(go2)
print(go3)


# Results with original __gen_id method
# name = 'GO1'   id = 'GameObject_0'
# name = 'GO2'   id = 'GameObject_1'
# name = 'GO3'   id = 'GameObject_2'


# Results with new simpler __gen_id method, __instance_counter not being incremented
# name = 'GO1'   id = 'GameObject_0'
# name = 'GO2'   id = 'GameObject_0'
# name = 'GO3'   id = 'GameObject_0'



More information about the Python-list mailing list