What's the difference between __iter__ and __getitem__?

前端 未结 3 1970
情书的邮戳
情书的邮戳 2020-12-14 03:01

This happens in Python 2.7.6 and 3.3.3 for me. When I define a class like this

class foo:
    def __getitem__(self, *args):
        print(*args)
3条回答
  •  借酒劲吻你
    2020-12-14 03:13

    __iter__ is the preferred way to iterate through an iterable object. If it is not defined the interpreter will try to simulate its behavior using __getitem__. Take a look here

提交回复
热议问题