Exceptions, assigning a tuple
Gonçalo Rodrigues
op73418 at mail.telepac.pt
Fri Nov 21 07:08:10 EST 2003
On Thu, 20 Nov 2003 23:56:49 -0800, Erik Max Francis <max at alcyone.com>
wrote:
>Derek Fountain wrote:
>
>> OK, and what gives it that ability? I tried tuple(f), where f was a
>> file
>> object. It gave me the contents of the file! I tried it again on an
>> instance of one of my own objects and got a "TypeError: iteration over
>> non-sequence" exception.
>>
>> It must be possible to give a class the ability to present itself as a
>> tuple. How is that done?
>
>The tuple function can work with instances which support an iterating
>interface. (This is why you were seeing this behavior with a file
>object; iterating over a file object gives you the lines in sequence.)
>
>>>> class C:
>... def __init__(self, x):
>... self.x = x
>... def __getitem__(self, i):
>... if i < self.x:
>... return i**2
>... else:
>... raise IndexError
>...
Hmm. More generally you have to implement __iter__ for a class to be
iterable, be in for loops => can be list-ified, tuple-ified,
etc.-ified.
>>> class C(object):
... def __init__(self, x):
... self.x = x
... def __iter__(self):
... return iter(range(self.x))
...
>>> c = C(9)
>>> for elem in c:
... print elem
...
0
1
2
3
4
5
6
7
8
>>> tuple(c)
(0, 1, 2, 3, 4, 5, 6, 7, 8)
>>> list(c)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> 2 in c
True
>>> "2" in c
False
>>>
With my best regards,
G. Rodrigues
More information about the Python-list
mailing list