Reputation: 2759
I do the following
class dumb(object):
def __init__(self):
self.g = {}
def __getitem__(self,key): return self.g[key] if key in self.g else None
def __setitem__(self,key,val):
self.g[key] = val
te = dumb()
te[1]=2
te[1]
Out[4]: 2
1 in te
and it hangs..
So if I want to search something like this, how do i do that? Please don't tell me to subclass class dictionary.
Thanks in advance!
Possible relevant question asked here: What does __contains__ do, what can call __contains__ function
Upvotes: 5
Views: 1878
Reputation: 4557
In order to be able to do something like:
1 in te
you have to define __contains__
method
class dumb(object):
def __init__(self):
self.g = {}
def __getitem__(self,key): return self.g[key] if key in self.g else None
def __setitem__(self,key,val):
self.g[key] = val
def __contains__(self, item):
return item in self.g
Upvotes: 3
Reputation: 500447
For in
to work correctly, you need to override __contains__()
:
class dumb(object):
...
def __contains__(self, key):
return key in self.g
By the way,
self.g[key] if key in self.g else None
can be more succinctly written as
self.g.get(key)
Upvotes: 8