Python Glossary Русский

all Python 3OOPfunction

__contains__

magic methods

The method behind in: x in obj calls obj.__contains__(x). Without it, in iterates over the whole object.

Syntax

def __contains__(self, item) -> bool: ...

Without __contains__ Python falls back to iteration — via __iter__ or __getitem__ — comparing items one by one, which is O(n). Your own __contains__ can make the check fast: sets and dicts answer in O(1). not in is the same call, negated.

Examples

class Range:
    def __init__(self, lo, hi):
        self.lo, self.hi = lo, hi
    def __contains__(self, x):
        return self.lo <= x < self.hi
r = Range(0, 10**9)
print(5 in r)  # → True — без перебора миллиарда чисел
print(-1 not in r)  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy