[Tutor] for x in myClass

Brian Christopher Robinson brian at dungeoncrawl.org
Tue Sep 2 01:50:33 EDT 2003


A friend of mine had an assignment to write a program that would take an 
array and create another array containing indexes into the first array, 
then sort the second array according to the values in the first array.  So, 
if you have the array:

[1, 50, 0, 42]

Your second array, called the tag array, would start out unsorted as:

[0, 1, 2, 3]

Then sorted it would be:

[2, 0, 3, 1]

I wanted to create a TagArray (really TagList, but he's working in VB and 
I'm working in Python, oh well) class.  So I wrote this:

class TagArray(list):
     def __init__(self, array):
         self.array = array
         for i in range(len(array)):
             self.append(i)

     def __getitem__(self, k):
         return self.array[list.__getitem__(self, k)]

     def __contains__(self, k):
         return k in self.array

This correctly refers to the original array when you use the bracket 
notation to get an element.  However, if you loop through it, you get the 
indexes instead of the values they're pointing to in the original array.  I 
overrode __contains__ which is the "in" statement, but apparently that's 
not the same one used when you do a for loop.  How can I override the 
elements returned when you have a statement like:

tag = TagArray([20, 30, 10, 0])
for x in tag:
         print x

this should print 20, 30, etc., not 0, 1, etc.  Also, will this cause the 
sort() method to work?


-- 
reaching out to embrace whatever may come 




More information about the Tutor mailing list