How to make a python array of specific objects

in java, the following code defines an array of a predefined class ( myCls ):

 myCls arr[] = new myCls 

how can i do this in python? I want to have an array of type ( myCls )?

early

+4
source share
2 answers

Python is dynamically typed. You do not need (and actually CANNOT) create a list containing only one type:

 arr = list() arr = [] 

If you only need to contain one type, you will have to create your own list by renaming the list methods and __setitem__() yourself.

+7
source

You can create arrays of only one type using array , but it is not intended to store custom classes.

The python way is to simply create a list of objects:

 a = [myCls() for _ in xrange(10)] 

You might want to take a look at fooobar.com/questions/254169 / ....

Note:

Be careful with these notations, IT IS NECESSARY WHAT YOU INTEND TO:

 a = [myCls()] * 10 

This will also create a list with a tenfold increase in the myCls object, but it will be ten times larger than one separate object, and not ten independently created objects.

+5
source

All Articles