【问题标题】:How can I make a class in python support __getitem__, but not allow iteration?如何在 python 中创建一个类支持 __getitem__,但不允许迭代?
【发布时间】:2010-10-29 22:15:17
【问题描述】:

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

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

cb = B()

for x in cb:
   print x

我可以向B 类添加什么来强制for x in cb: 失败?

【问题讨论】:

  • 只是问这个,然后回答它,以防其他人需要知道如何做到这一点。
  • 出于好奇,为什么您要授予对 getitem 的访问权限但不使其可迭代?你的用例是什么?
  • 我有一个类,其行为类似于字典,但不继承自字典。因此我定义了 getitem,如果有人试图迭代它,我希望它出错,而不是开始尝试用整数调用 getitem。需要明确的是,这不是我选择实现这个特定类的方式,但我的决定被覆盖了。

标签: python operator-overloading iteration


【解决方案1】:

从这个question的答案可以看出,如果存在__getitem__,__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

【讨论】:

  • 如果有比这更 Pythonic 的答案,我很乐意接受。
  • 你的类名是否正确大写,那会更pythonic
【解决方案2】:

我认为一个更好的解决方案是引发 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 用于正确使用新型类(以及该方法的整体优点)。
  • 可悲的是,这使得 isinstance(a, collections.Iterable) 返回 True :(
猜你喜欢
  • 2017-08-23
  • 1970-01-01
  • 2011-01-18
  • 2011-01-03
  • 1970-01-01
  • 2012-03-13
  • 2021-09-30
  • 2015-04-28
  • 1970-01-01
相关资源
最近更新 更多