[Tutor] making object iterable

Alex Hall mehgcap at gmail.com
Sun Feb 6 02:59:32 CET 2011


On 2/5/11, bob gailer <bgailer at gmail.com> wrote:
> On 2/5/2011 2:46 PM, Alex Hall wrote:
>> Hi all,
>> I have a class which has a list as an attribute, meaning you must say
>> something like:
>> for result in obj.results: ...
>> I want to make life a bit easier and let users just say:
>> for result in obj: ...
>> Here is what I have tried to make my class into an iterable one, yet I
>> get an error saying that the class does not support indexing:
>>
>>   def __iter__(self):
>>    #makes this class indexable instead of having to use its "results" list
>>    return self.iterate()
>>
>>   def iterate(self):
>>    i=0
>>    while i<len(self.results):
>>     yield self.results[i]
>>     i+=1
>>
> Have you considered subclassing list? That would solve many problems.
Well, it seems to be working now. Subclassing list would have probably
worked, and I never thought of that. I have other attributes as well,
though, not just the list of results. For example, there is a "url"
string, a "pages" int, andso on. I am not sure if I could have mixed a
list subclass with these other attributes...
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


More information about the Tutor mailing list