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
__getitem__(x, i) . The method __getitem__(self, key) defines behavior for when an item is accessed, using the notation self[key] . This is also part of both the mutable and immutable container protocols. Unlike some other languages, Python basically lets you pass any object into the indexer.
Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.
__getitem__ and __setitem__ in Python They are predefined methods that simplify many operations that can be performed on a class instance, like __init__(), __str__(), __call__() etc. These methods are very helpful because they are used in binary operations, assignment operations, unary and binary comparison operations.
The __index__ method implements type conversion to an int when the object is used in a slice expression and the built-in hex , oct , and bin functions.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With