I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.
So, my question:
How can I automatically give a name to an object?
I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...
you could make an 'animal' class with a name attribute.
Or
you could programmically define the class like so:
Found this: http://www.gamedev.net/community/forums/topic.asp?topic_id=445037
If you need a way to refer to them individually, it's relatively common to have the class give each instance a unique identifier on initialization:
Like this?
At this point, herd will have 10,000 distinct instances of the
Animal
class.Hm, well you normally just stuff all those instances in a list and then iterate over that list if you want to do something with them. If you want to automatically keep track of each instance created you can also make the adding to the list implicit in the class' constructor or create a factory method that keeps track of the created instances.
Any instance could have a name attribute. So it sounds like you may be asking how to dynamically name a class, not an instance. If that's the case, you can explicitly set the __name__ attribute of a class, or better yet just create the class with the builtin type (with 3 args).
would be equivalent to