我正在编写一个包装字典的自定义类。因此,我想为它实现getitem。我也将使用元组作为这个字典中的键。但是,当我尝试将元组传递给 getitem 时,Python 会抛出 KeyError。当我将元组传递给getitem时,它看起来像是将我的元组转换为一个 int :
代码:
Class Board(object):
def __getitem__(self, key):
print "type in call: " + type(key)
return self.board[key]
# in main somewhere
board = Board()
print "type before call: " + type((1, 2))
if (1, 2) in board:
print "It's there!"
输出:
type before call: <type 'tuple'>
type in call: <type 'int'>
## traceback stuff ##
KeyError: 0
Board 是否需要继承映射类型才能让 Python 满意?另外,为什么 Python 一开始就尝试这样做?