Bug? If not, how to work around it?
Bengt Richter
bokr at oz.net
Thu Aug 7 04:46:54 EDT 2003
On Wed, 06 Aug 2003 20:40:25 +0100, Gonçalo Rodrigues <op73418 at mail.telepac.pt> wrote:
>Hi,
>
>Consider the following class:
>
>>>> class Test(object):
>... def __init__(self, obj):
>... self.__obj = obj
>... def __getattr__(self, name):
>... return getattr(self.__obj, name)
>...
>
>Now:
>
>>>> a = Test([])
>>>> a.__iter__
><method-wrapper object at 0x0112CF30>
>>>> iter(a)
>Traceback (most recent call last):
> File "<interactive input>", line 1, in ?
>TypeError: iteration over non-sequence
>>>>
>
>Is this a bug? If not, how to code Test such that iter sees the
>__iter__ of the underlying object?
>
Perhaps this way?
>>> class Test(object):
... def __init__(self, obj):
... self.__obj = obj
... def __getattribute__(self, name):
... return getattr(object.__getattribute__(self, '_Test__obj'), name)
... def __iter__(self):
... return iter(object.__getattribute__(self, '_Test__obj'))
...
>>> a = Test([11, 22])
>>> a.__iter__
<method-wrapper object at 0x00902DB0>
>>> iter(a)
<listiterator object at 0x00902C50>
>>> for i in a: print i,
...
11 22
>>> b = Test('abc')
>>> for c in b: print `c`,
...
'a' 'b' 'c'
>>> c = Test(123)
>>> for x in c: print x
...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 7, in __iter__
TypeError: iteration over non-sequence
>>>
Regards,
Bengt Richter
More information about the Python-list
mailing list