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