Many instances of a class

人盡茶涼 提交于 2019-12-05 16:25:43
Grumbel

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})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!