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...
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.
Like this?
class Animal( object ):
pass # lots of details omitted
herd= [ Animal() for i in range(10000) ]
At this point, herd will have 10,000 distinct instances of the Animal
class.
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:
>>> import itertools
>>> class Animal(object):
... id_iter = itertools.count(1)
... def __init__(self):
... self.id = self.id_iter.next()
...
>>> print(Animal().id)
1
>>> print(Animal().id)
2
>>> print(Animal().id)
3
you could make an 'animal' class with a name attribute.
Or
you could programmically define the class like so:
from new import classobj
my_class=classobj('Foo',(object,),{})
Found this: http://www.gamedev.net/community/forums/topic.asp?topic_id=445037
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).
class Ungulate(Mammal):
hoofed = True
would be equivalent to
cls = type('Ungulate', (Mammal,), {'hoofed': True})
来源:https://stackoverflow.com/questions/405282/many-instances-of-a-class