What does __contains__ do, what can call __contains__ function

前端 未结 5 864
鱼传尺愫
鱼传尺愫 2020-11-30 01:17

Here is my code:

class a(object):
    d=\'ffffd\'
    def __contains__(self):
        if self.d:return True
b=a()
print b.contains(\'d\')  # error
print contai         


        
5条回答
  •  醉酒成梦
    2020-11-30 01:37

    __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  
    

提交回复
热议问题