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:失效?
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