我想定义一个支持__getitem__
的类,但不允许迭代。
例如:
class B:
def __getitem__(self, k):
return k
cb = B()
for x in cb:
print x
我可以添加哪些内容B
来强制for x in cb:
失败?
答案 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