array of class

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Jan 2 17:22:10 EST 2007


mm a écrit :
> 
> How can I do a array of class?

s/array/list/

> s1=[]  ## this array should hold classes
> 
> ## class definition
> class Word:
>   word=""
> 
> 
> ## empty words... INIT
> for i in range(100):  ## 0..99
>   s1.append(Wort)

I guess that s/Wort/Word/

> s1[0].word="There"
> s1[1].word="should"
> s1[2].word="be"
> s1[3].word="different"
> s1[4].word="classes"
> 
> ... but it's not.

Err... Are you sure you really understand what's a class is and how it's 
supposed to be used ?

> 
> print s1
> ------------
> [<class __main__.Wort at 0x7ff1492c>,
> <class __main__.Wort at 0x7ff1492c>,
> <class __main__.Wort at 0x7ff1492c>,
> <class __main__.Wort at 0x7ff1492c>,
> <class __main__.Wort at 0x7ff1492c>,
> <class __main__.Wort at 0x7ff1492c>,
> ........
> -----------
> 
> Here, this "classes" are all at the same position in memory.

Of course. You created a list of 100 references to the same class.

> So there 
> are no different classes in the array.

How could it be ? When did you put another class in the list ?

> So I access with s1[0], s1[1], s1[2], etc. always the same data.

Of course.

> Any idea?

Yes : read something about OO base concepts like classes and instances, 
then read the Python's tutorial about how these concepts are implemented 
in Python.

FWIW, I guess that what you want here may looks like this:

class Word(object):
   def __init__(self, word=''):
     self._word = word
   def __repr__(self):
     return "<Word %s at %d>" % (self._word, id(self))


words = []
for w in ['this', 'is', 'probably', 'what', 'you', 'want']:
   words.append(Word(w))
print words



More information about the Python-list mailing list