ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-Tutor
python-Tutor
[Tutor] for x in myClass
by Brian Christopher Robinson other posts by this author
Sep 2 2003 4:50AM messages near this date
Re: [Tutor] Compiling Python to Native Machine Code | Re: [Tutor] for x in myClass
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 


_______________________________________________
Tutor maillist  -  Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Brian Christopher Robinson
Danny Yoo
Terry Carroll
Danny Yoo
Danny Yoo

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved