我想定义一个支持__getitem__
但不允许迭代的类。例如:
class B:
def __getitem__(self, k):
return k
cb = B()
for x in cb:
print x
我可以在课堂上添加什么B
来强制for x in cb:
失败?
我想定义一个支持__getitem__
但不允许迭代的类。例如:
class B:
def __getitem__(self, k):
return k
cb = B()
for x in cb:
print x
我可以在课堂上添加什么B
来强制for x in cb:
失败?
我认为更好的解决方案是引发 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
从这个问题的答案可以看出,如果存在,__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