Creating alot of class instances?

Tim Chase python.list at tim.thechases.com
Sun Jul 5 17:07:45 EDT 2009


>> For example lets say I have
>>
>> class MyMaterials:
>>
>> and my instances might need to look like
>>
>> material_01
>> material_02
>> or
>> light_01
>> light_02
>> or
>> Mesh_01
>> Mesh_02 etc
> 
> If you do not know how many instances you are going to create from the
> beginning, there is no way for you to know which of the instances you mentioned
> above will get created. So having names for all of the instances will not help
> you since you will never know what names are "safe" to use.
> 
> On the other hand, if you have all instances in a list, you can refer to them
> by index and you know exactly how many of them you have.
> 
> If you would like to get instances by some name you gave to them, maybe
> something like this will work:
> 
> def get_instance(name):
>     for instance in instance_list:
>         if instance.name == name:
>             return instance
>     return None

Another option might be to use a counter in the class that keeps 
track of the number of instances:

   class MyMaterial:
     instances = 0
     def __init__(self, name):
       self.name = name
       self.instance = MyMaterial.instances
       MyMaterial.instances += 1
     def __str__(self):
       return "%s_%02i" % (self.name, self.instance)

   m = MyMaterial("Brick")
   print m
   # "Brick_00"
   print repr([MyMaterial("Stone") for _ in range(5)])
   # "[Stone_01, Stone_02, Stone_03, Stone_04, Stone_05]"

It's not thread-safe, but it may do the trick.

-tkc






More information about the Python-list mailing list