Many instances of a class

2019-05-07 13:24发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

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


回答4:

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



回答5:

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})