Moayyad Yaghi
Moayyad Yaghi

Reputation: 3722

how to make a python array of particular objects

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

Upvotes: 4

Views: 10592

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798706

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.

Upvotes: 7

catchmeifyoutry
catchmeifyoutry

Reputation: 7369

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.

Upvotes: 5

Related Questions