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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

but you CAN create arrays of only integers, double, etc. types in python
I don't think that the OP cares about the difference between arrays and lists.
The statement that you cannot is false, however.
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: 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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.