如何在python支持__getitem__中创建一个类,但不允许迭代?

gri*_*eve 3 python iteration operator-overloading

我想定义一个支持__getitem__但不允许迭代的类.例如:

class B:
   def __getitem__(self, k):
      return k

cb = B()

for x in cb:
   print x
Run Code Online (Sandbox Code Playgroud)

我可以在课堂B上添加什么来强制for x in cb:失败?

Ric*_*and 14

我认为稍微好一点的解决方案是引发TypeError而不是普通异常(这是通常在非可迭代类中发生的情况:

class A(object):
    # show what happens with a non-iterable class with no __getitem__
    pass

class B(object):
    def __getitem__(self, k):
        return k
    def __iter__(self):
        raise TypeError('%r object is not iterable'
                        % self.__class__.__name__)
Run Code Online (Sandbox Code Playgroud)

测试:

>>> iter(A())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'A' object is not iterable
>>> iter(B())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "iter.py", line 9, in __iter__
    % self.__class__.__name__)
TypeError: 'B' object is not iterable
Run Code Online (Sandbox Code Playgroud)