English 中文(简体)
我怎么能够把一个班子用于支持__ 植被项目__但不允许它使用?
原标题:
  • 时间:2009-05-29 15:45:35
  •  标签:

I want to define a class that supports __getitem__, but does not allow iteration. for example:

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

cb = B()

for x in cb:
   print x

在<代码>B上,我可以添加什么内容,使<代码>在cb中的x:失效?

最佳回答

我认为,一种稍微更好的解决办法是提出一种类型错误,而不是一种简单的例外情况(通常情况下是非可转让类别的情况):

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
问题回答




相关问题
热门标签