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

时间:2009-05-29 15:45:35

标签: python operator-overloading iteration

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

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

cb = B()

for x in cb:
   print x

我可以添加哪些内容B来强制for x in cb:失败?

2 个答案:

答案 0 :(得分: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__)

测试:

>>> 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

答案 1 :(得分:2)

从这个question的答案中,我们可以看到__iter__将在__getitem__之前被调用(如果它存在),所以只需将B定义为:

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

   def __iter__(self):
      raise Exception("This class is not iterable")

然后:

cb = B()
for x in cb: # this will throw an exception when __iter__ is called.
  print x