ブール値のインデックスを許可しない独自のリストを定義できます。
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)
インスタンスを作成します。
>>> L = MyList([1, 2, 3])
整数が機能します:
>>> 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.
それに応じてオーバーライド__setitem__
して、ブール値をインデックスとして値を設定しないようにします。