Hướng dẫn python __contains__ vs in

I was wondering if some one could explain the difference between the "in" keyword of Python and the contains method

I was working with a sample list and found this behavior. When are the two supposed to be used? Is there some efficiency that can be achieved if I use one over the other.

    >>> my_list = ["a", "b", "c"]
    >>> my_list.__contains__["a"]
    True
    >>> "a" in my_list
    True

madhead

29.5k15 gold badges147 silver badges190 bronze badges

asked May 14, 2013 at 5:37

1

From the docs:

For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.

string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find[x] != -1.

For user-defined classes which define the __contains__[] method, x in y is true if and only if y.__contains__[x] is true.

For user-defined classes which do not define __contains__[] but do define __iter__[], x in y is true if some value z with x == z is produced while iterating over y. If an exception is raised during the iteration, it is as if in raised that exception.

Lastly, the old-style iteration protocol is tried: if a class defines __getitem__[], x in y is true if and only if there is a non-negative integer index i such that x == y[i], and all lower integer indices do not raise IndexError exception.

answered May 14, 2013 at 5:43

HennyHHennyH

7,5842 gold badges28 silver badges38 bronze badges

The __contains__[] method of an an object is called when you use the in statement.

For lists this is pre-defined, but you can also define your own class, add a __contains__ method and use in on the instances of that class.

You should be using in and not call __contains__[] directly.

omz

53k5 gold badges127 silver badges139 bronze badges

answered May 14, 2013 at 5:38

AnthonAnthon

62.2k28 gold badges173 silver badges231 bronze badges

Like most magic methods, the __contains__ method is not meant to be called directly. The reason __contains__ exists is precisely so that you can write obj in container instead of having to use method-call syntax. So you should use obj in container.

answered May 14, 2013 at 5:39

BrenBarnBrenBarn

232k35 gold badges396 silver badges373 bronze badges

Doing "a" in my_list actually calls __contains__ method of my_list if defined.

If __contains__ is not defined then __getitem__ is used.

answered May 14, 2013 at 5:38

Ashwini ChaudharyAshwini Chaudhary

236k55 gold badges442 silver badges495 bronze badges

Not the answer you're looking for? Browse other questions tagged python or ask your own question.

Here is my code:

class a[object]:
    d='ddd'
    def __contains__[self]:
        if self.d:return True
b=a[]
print b.contains['d']  # error
print contains[b,'d']  # error

Chris Martin

29.6k8 gold badges74 silver badges131 bronze badges

asked Dec 27, 2009 at 1:49

Like all special methods [with "magic names" that begin and end in __], __contains__ is not meant to be called directly [except in very specific cases, such as up=calls to the superclass]: rather, such methods are called as part of the operation of built-ins and operators. In the case of __contains__, the operator in question is in -- the "containment check" operator.

With your class a as you present it [except for fixing your typo, and using True instead of true!-], and b as its instance, print 'x' in b will print True -- and so will any other containment check on b, since b always returns True [because self.d, a non-empty string, is true].

answered Dec 27, 2009 at 2:04

Alex MartelliAlex Martelli

821k163 gold badges1200 silver badges1377 bronze badges

to get your code to do something [although nothing useful]:

class a[object]:

    d = 'ddd'

    def __contains__[self, m]:
        if self.d: 
            return True

b = a[]

>>> 'd' in b
True

The docs.

Julius

7997 silver badges11 bronze badges

answered Dec 27, 2009 at 1:51

cobbalcobbal

68.9k19 gold badges142 silver badges155 bronze badges

__contains__ method defines how instances of class behave when they appear at right side of in and not in operator.

class Person[object]:
      def __init__[self,name,age]:
          self.name = name
          self.age = age
      def __contains__[self,param1]:
          return True if param1 in self.__dict__.keys[] else False

>>> p = Person['Robby Krieger',23]
>>> 'name' in p
True  

Azat Ibrakov

8,8669 gold badges37 silver badges45 bronze badges

answered Jan 1, 2013 at 9:33

vijay shankervijay shanker

2,3781 gold badge21 silver badges37 bronze badges

1

if self.d:return true

self.d is the string 'ddd'. Non-empty strings are always truthy: when you use if on 'ddd' it will always act as if you'd said if True:.

I think what you probably meant is:

def __contains__[self, item]:
    return item in self.d

in is the operator that calls the __contains__ method behind the scenes.

answered Dec 27, 2009 at 1:56

bobincebobince

518k102 gold badges644 silver badges825 bronze badges

Lets see a very simple example of magic method __contains__ :

Suppose I have class Player and my __init__ method takes one string argument name. In main I have created an object [obj1] of class Player.

Now if I want to know if my obj1 [in this case attribute name of obj1] contains a particular string, substring or an alphabet, I have to implement __contains__ method as shown in the example.

If my class has __contains__ method I can call built-in operator in on my custom objects as shown in the example.

   class Player[]:

    def __init__[self, name]:
        self.name=name

    def __contains__[self, substring]:
        if substring in self.name:
            return True
        else:
            return False

obj1=Player["Sam"]
print ['am' in obj1]    ----> True
print ['ami' in obj1]   ----> False

answered Jul 29, 2016 at 10:00

N RandhawaN Randhawa

7,9833 gold badges41 silver badges47 bronze badges

Not the answer you're looking for? Browse other questions tagged python or ask your own question.

Chủ Đề