在构造函数中分配了__iter__的类未识别为迭代器 [英] class with __iter__ assigned in constructor not recognized as iterator

查看:106
本文介绍了在构造函数中分配了__iter__的类未识别为迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于迭代器的怪异问题.在调查另一个问题时,我发现了以下内容.这是一个有效的迭代器:

Kind of a weird question about iterators. While investigating a different question, I found the following. Here is an iterable that works:

class CacheGen(object):
    def __init__(self, iterable):
        if isinstance(iterable, (list, tuple, dict)):
            self._myiter = iterable
        else:
            self._myiter = list(iterable)
    def __iter__(self):
        return self._myiter.__iter__()
    def __contains__(self, key):
        return self._myiter.__contains__(key)
    def __getitem__(self, key):
        return self._myiter.__getitem__(key)

这里有一个类似的迭代器,但没有:

Here is a similar iterable that doesn't:

class CacheGen2(object):
    def __init__(self, iterable):
        if isinstance(iterable, (list, tuple, dict)):
            self._myiter = iterable
        else:
            self._myiter = list(iterable)
        self.__iter__ = self._myiter.__iter__
        self.__contains__ = self._myiter.__contains__
        self.__getitem__ = self._myiter.__getitem__

请注意,他们实际上是在做同一件事,但是一个委托,另一个只是将我的类构造函数分配给列表的那个.有什么想法吗?请注意,它在类中具有 iter 函数,我可以直接调用它并获得有效的迭代器,但是'normal'函数不起作用.

Note that they are really doing about the same thing, but one delegates, and the other just assigns my class constructor to the list's. Any ideas why? Note that it has an iter function in the class, I can call it directly and get a valid iterator, but the 'normal' functions don't work.

xr = xrange(100)
cg = CacheGen(xr)
list(cg)
[0,1,2,3...

cg2 = CacheGen2(xr)
list(cg2)
TypeError                                 Traceback (most recent call last)
<ipython-input-83-1f4da2c55acb> in <module>()
----> 1 list(cg2)

TypeError: 'CacheGen2' object is not iterable

cg2.__iter__
<method-wrapper '__iter__' of list object at 0x0000000006695C08>

cg2.__iter__()
<listiterator at 0x669c438>

iter(cg2)
TypeError                                 Traceback (most recent call last)
<ipython-input-86-b62853ce1dab> in <module>()
----> 1 iter(cg2)

TypeError: 'CacheGen2' object is not iterable

推荐答案

在类而不是实例上查找像__iter__这样的魔术方法,因此在self上分配它们是行不通的.它们必须实际存在于类中.

Magic methods like __iter__ are looked up on the class, not the instance, so it doesn't work to assign them on self. They have to actually exist on the class.

这篇关于在构造函数中分配了__iter__的类未识别为迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆