Python __contains__() Method
The __contains__() Method
The __contains__() method controls what the in operator checks for your own objects.
Example
Check if an employee is in a Company:
class Company:
def __init__(self, employees):
self.employees = employees
def __contains__(self, name):
return name in self.employees
c1 = Company(["Emil", "Tobias", "Linus"])
print("Emil" in c1)
Try it Yourself »
Without __contains__()
Without __contains__(), using in on a custom object raises an error:
Example
Remove __contains__(), and the check fails:
class Company:
def __init__(self, employees):
self.employees = employees
c1 = Company(["Emil", "Tobias", "Linus"])
print("Emil" in c1)
Try it Yourself »