Many class instances

I am trying to write a simulation of life in python with many animals. It is impossible to name each instance of the classes that I am going to use, because I do not know how many there will be.

So my question is:

How can I automatically assign a name to an object?

I was thinking of creating a Hurd class that could be all animals of this type at the same time ...

+4
source share
5 answers

Hm, well, as a rule, you just populate all these instances in the list, and then iterate over this list if you want to do something with them. If you want to automatically track each instance created, you can also make the list add implicit in the class constructor or create a factory method that tracks the created instances.

+8
source

Like this?

class Animal( object ): pass # lots of details omitted herd= [ Animal() for i in range(10000) ] 

At that moment, the herd will have 10,000 different instances of the Animal class.

+5
source

If you need a way to access them individually, it’s relatively conditional that the class gives each instance a unique identifier during 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
source

you can create a class 'animal' with the name attribute.

or

you can program the class as follows:

 from new import classobj my_class=classobj('Foo',(object,),{}) 

Found: http://www.gamedev.net/community/forums/topic.asp?topic_id=445037

+2
source

Any instance can have a name attribute. Looks like you might be asking how to dynamically name a class, not an instance. In this case, you can explicitly specify the __name__ attribute of the class, or even better, create a class with a built-in type (with 3 arguments).

 class Ungulate(Mammal): hoofed = True 

will be equivalent

 cls = type('Ungulate', (Mammal,), {'hoofed': True}) 
+1
source

All Articles