为什么在类上定义 __getitem__ 会使其可迭代?
Why does defining __getitem__ on a class make it iterable?
例如,如果我写:
class b:
def __getitem__(self, k):
return k
cb = b()
for k in cb:
print k
我得到了输出:
0
1
2
3
4
5
6
7
8
...
我真的希望看到for k in cb:"返回错误
I would really expect to see an error returned from "for k in cb:"
如果你看看 PEP234 定义迭代器,它说:
If you take a look at PEP234 defining iterators, it says:
1. An object can be iterated over with "for" if it implements
__iter__() or __getitem__().
2. An object can function as an iterator if it implements next().
这篇关于为什么在类上定义 __getitem__ 使其在 python 中可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在python中的感兴趣区域周围绘制一个矩形How to draw a rectangle around a region of interest in python(如何在python中的感兴趣区域周围绘制一个矩形)
如何使用 OpenCV 检测和跟踪人员?How can I detect and track people using OpenCV?(如何使用 OpenCV 检测和跟踪人员?)
如何在图像的多个矩形边界框中应用阈值?How to apply threshold within multiple rectangular bounding boxes in an image?(如何在图像的多个矩形边界框中应用阈值?)
如何下载 Coco Dataset 的特定部分?How can I download a specific part of Coco Dataset?(如何下载 Coco Dataset 的特定部分?)
根据文本方向检测图像方向角度Detect image orientation angle based on text direction(根据文本方向检测图像方向角度)
使用 Opencv 检测图像中矩形的中心和角度Detect centre and angle of rectangles in an image using Opencv(使用 Opencv 检测图像中矩形的中心和角度)