4

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

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Moayyad Yaghi
  • 3,622
  • 13
  • 51
  • 67

2 Answers2

7

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.

Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    but you CAN create arrays of only integers, double, etc. types in python – catchmeifyoutry Dec 27 '09 at 11:00
  • 2
    I don't think that the OP cares about the difference between arrays and lists. – Georg Schölly Dec 27 '09 at 11:05
  • 1
    The statement that you cannot is false, however. – bayer Dec 27 '09 at 11:47
  • 2
    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 Dec 27 '09 at 11:50
  • 1
    @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. – tzot Dec 27 '09 at 13:36
5

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.

Community
  • 1
  • 1
catchmeifyoutry
  • 7,179
  • 1
  • 29
  • 26