I'm writing a custom class that wraps a dict. As such, I want to implement getitem for it. I also will be using tuples as keys in this dict. However, when I try to pass a tuple to getitem, Python throws a KeyError. It looks like it's casting my tuple to an int when I pass it to getitem :
Code:
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!"
Ouptut:
type before call: <type 'tuple'>
type in call: <type 'int'>
## traceback stuff ##
KeyError: 0
Does Board need to inherit from a mapping type for Python to be happy? Also, why does Python try to do this cast in the first place?
Containment iterates unless __contains__()
is implemented. So, implement it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.