Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does __contains__ do, what can call __contains__ function

Tags:

python

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
like image 211
zjm1126 Avatar asked Dec 27 '09 01:12

zjm1126


4 Answers

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

like image 194
Alex Martelli Avatar answered Oct 18 '22 07:10

Alex Martelli


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.

like image 33
cobbal Avatar answered Oct 18 '22 05:10

cobbal


__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  
like image 23
vijay shanker Avatar answered Oct 18 '22 05:10

vijay shanker


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.

like image 8
bobince Avatar answered Oct 18 '22 05:10

bobince