P
P
Paul Smith @Paul2013-01-30 12:30:48
Python
Paul Smith @Paul, 2013-01-30 12:30:48

Python. How to get an array of object instances of a class?

I create a class:

class myClass:
  x = 0
  def myMethod(self):
  x+=1

I'm trying to create instances of the class in a loop and put them in an array:
for x in range(1,10):
  myArray.append(myClass)

Either like this:
for x in range(1,10):
  myArray.append(0)
  myArray[-1] = myClass

In both cases it throws an error.
Googled a lot, and did not understand how I can create an arbitrary number of objects with the possibility of further access to them.
In python the first week, do not throw stones =)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
dotsquid, 2013-01-30
Smith

And what error does it give?
Probably, before the loop, you need to indicate that myArray is a list.

myArray = []

U
un1t, 2013-01-30
@un1t

myArray.append(myClass)

You are not creating objects here. And add a link to the class to the list.
Need like this:
myArray.append(myClass())

N
Nikolay Shamanovich, 2014-02-08
@Shm13

def myMethod(self):
x+=1

Forgot about indents?
And on the topic, you can:
>>> class test:
...     def __repr__(self):
...             return 'object!'
... 
>>> [test() for x in range(10)]
[object!, object!, object!, object!, object!, object!, object!, object!, object!, object!]
>>>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question