为什么`__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.
相关文章