views:

109

answers:

2

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

myCls arr[] = new myCls

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

thanks in advance

+5  A: 

Python is dynamically typed. You do not need to (and in fact CAN'T) create a list that only contains a single type:

arr = list()
arr = []

If you require it to only contain a single type then you'll have to create your own list-alike, reimplementing the list methods and __setitem__() yourself.

Ignacio Vazquez-Abrams
but you CAN create arrays of only integers, double, etc. types in python
catchmeifyoutry
I don't think that the OP cares about the difference between arrays and lists.
Georg
The statement that you cannot is false, however.
bayer
No, it isn't. list does not care what class it contains. Yes, you can create a list-alike that only accepts a single type, or use array.array, but neither of those is a list.
Ignacio Vazquez-Abrams
@Ignacio: indeed your "CAN'T" statement as specified is false. In python, you CAN create a list that contains items of a single type; what you can't, is you CAN'T ENFORCE the list items to be of a single type.
ΤΖΩΤΖΙΟΥ
+3  A: 

You can only create arrays of only a single type using the array package, but it is not designed to store user-defined classes.

The python way would be to just create a list of objects:

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

You might want to take a look at this stackoverflow question.

NOTE:

Be careful with this notation, IT PROBABLY DOES NOT WHAT YOU INTEND:

a = [myCls()] * 10

This will also create a list with ten times a myCls object, but it is ten times THE SAME OBJECT, not ten independently created objects.

catchmeifyoutry