class MyList(list):
def __getitem__(self, item):
if isinstance(item, bool):
raise TypeError('Index can only be an integer got a bool.')
# in Python 3 use the shorter: super().__getitem__(item)
return super(MyList, self).__getitem__(item)
举个例子:
^{pr2}$
整数起作用:
>>> L[1]
2
但是True没有:
>>> L1[True]
-
TypeError Traceback (most recent call last)
<ipython-input-888-eab8e534ac87> in <module>()
> 1 L1[True]
<ipython-input-876-2c7120e7790b> in __getitem__(self, item)
2 def __getitem__(self, item):
3 if isinstance(item, bool):
> 4 raise TypeError('Index can only be an integer got a bool.')
TypeError: Index can only be an integer got a bool.
您可以定义自己的不允许布尔索引的列表:
举个例子:
^{pr2}$整数起作用:
但是
True
没有:相应地重写
__setitem__
以防止设置布尔值作为索引。在相关问题 更多 >
编程相关推荐