__contains__

Dunder MethodPython 2.0+Intermediate

Called by the 'in' operator to test membership

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

python
class NumberRange:
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __contains__(self, item):
        return self.start <= item <= self.end

r = NumberRange(1, 10)
print(5 in r)
print(15 in r)

__contains__ called by the 'in' operator to test membership. Implementing it lets you customize how Python interacts with your objects.

Try in Playground

Tags

oopmagic-methodprotocolcore