I have subclass that inherits from a dict. On __getitem__ method I’d like to check whether the key is numeric or not. If it is numeric I’d like to implement some other behavior and if it not then I’d like continue as it would normally do. Example:
class M(dict):
...
def __getitem__(self, key):
if self.isNumber(key):
print "I am number"
else:
# continue the same way as it would have done
...
>>> x = M({"name": "Tom", "surname": "Baker", "age": "55"})
>>> print x["name"]
Tom
>>> x[0]
I am number
How can I do this?
UPDATE
I know that items in dict are hashed therefore it will not be in order, the reason behind what I ask is something else. And since I’m sure you’ll still ask why, this is the reason: The dict is an object and I will retrieve the objects related to the given object by their index. (Think as parent, child stuff)
Not sure if this is what you are looking for…
As mentioned by @bpgergo, you can also use
super.So the return would look like this:
The big difference here is that my way would (perhaps poorly) suppress any KeyError that was raised because you tried to access a key that does not exist.