Many instances of a class

2019-05-07 13:43发布

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

5条回答
萌系小妹纸
2楼-- · 2019-05-07 13:54

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

查看更多
别忘想泡老子
3楼-- · 2019-05-07 13:56

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
查看更多
Luminary・发光体
4楼-- · 2019-05-07 13:57

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.

查看更多
乱世女痞
5楼-- · 2019-05-07 14:00

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.

查看更多
甜甜的少女心
6楼-- · 2019-05-07 14:20

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})
查看更多
登录 后发表回答