What does __contains__ do, what can call __contains__ function

前端 未结 5 848
鱼传尺愫
鱼传尺愫 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条回答
  •  -上瘾入骨i
    2020-11-30 01:42

    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
    

提交回复
热议问题