Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: using __getitem__ in a class and using in to find that item

Tags:

python

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

like image 689
user2290820 Avatar asked Oct 16 '13 14:10

user2290820


People also ask

What does __ Getitem __ do in Python?

__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.

What is the __ str __ method in Python?

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.

What is __ Setitem __?

__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.

What is __ index __ method in Python?

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.


2 Answers

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)
like image 185
NPE Avatar answered Oct 06 '22 18:10

NPE


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
like image 36
Alexander Zhukov Avatar answered Oct 06 '22 17:10

Alexander Zhukov