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
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
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.
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.