Why `__iter__` does not work when defined as an instance variable?(为什么`__iter__`在定义为实例变量时不起作用?)
问题描述
如果我如下定义 __iter__ 方法,它将不起作用:
If I define the __iter__ method as follows, it won't work:
class A:
def __init__(self):
self.__iter__ = lambda: iter('text')
for i in A().__iter__():
print(i)
iter(A())
结果:
t
e
x
t
Traceback (most recent call last):
File "...mytest.py", line 10, in <module>
iter(A())
TypeError: 'A' object is not iterable
如您所见,调用 A().__iter__() 有效,但 A() 不可迭代.
As you can see, calling A().__iter__() works, but A() is not iterable.
但是,如果我为该类定义 __iter__,那么它将起作用:
However if I define __iter__ for the class, then it will work:
class A:
def __init__(self):
self.__class__.__iter__ = staticmethod(lambda: iter('text'))
# or:
# self.__class__.__iter__ = lambda s: iter('text')
for i in A():
print(i)
iter(A())
# will print:
# t
# e
# x
# t
有谁知道为什么 python 是这样设计的?即为什么 __iter__ 作为实例变量不起作用?你不觉得它不直观吗?
Does anyone know why python has been designed like this? i.e. why __iter__ as instance variable does not work? Don't you find it unintuitive?
推荐答案
这是按设计完成的.您可以在此处找到详细说明:https://docs.python.org/3/reference/datamodel.html#special-method-lookup
It is done by design. You can find the thorough description here: https://docs.python.org/3/reference/datamodel.html#special-method-lookup
简短的回答:必须在类对象本身上设置特殊方法,以便解释器始终如一地调用.
Short answer: the special method must be set on the class object itself in order to be consistently invoked by the interpreter.
长答案:这背后的想法是加快众所周知的建设.在你的例子中:
Long answer: the idea behind this is to speed up well-known constructions. In your example:
class A:
def __init__(self):
self.__iter__ = lambda: iter('text')
在现实生活中,您多久会编写一次这样的代码?所以,Python 做了什么 - 它跳过了实例的字典查找,即 iter(A()) 根本没有看到"那个 self.__iter__,它实际上是self.__dict__['__iter__'] 在这种情况下.
How often are you going to write a code like this in real life? So, what Python does - it skips a dictionary lookup of the instance, i.e. iter(A()) simply does not "see" that self.__iter__, which is actually self.__dict__['__iter__'] in this case.
它还跳过了所有 __getattribute__ 实例和元类查找,获得了显着的加速.
It also skips all the __getattribute__ instance and metaclass lookup gaining a significant speedup.
这篇关于为什么`__iter__`在定义为实例变量时不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么`__iter__`在定义为实例变量时不起作用?
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
