__contains__ — Intermediate Examples
Called by the 'in' operator to test membership
Real-world __contains__ usage
A practical example using __contains__ in a realistic class.
python
# Real-world __contains__ usage class Money: def __init__(self, amount, currency="USD"): self.amount = amount self.currency = currency def __repr__(self): return f"Money({self.amount}, '{self.currency}')" def __str__(self): symbols = {"USD": "$", "EUR": "€", "GBP": "£"} sym = symbols.get(self.currency, self.currency) return f"{sym}{self.amount:.2f}" def __add__(self, other): if self.currency != other.currency: raise ValueError(f"Cannot add {self.currency} and {other.currency}") return Money(self.amount + other.amount, self.currency) def __eq__(self, other): return self.amount == other.amount and self.currency == other.currency def __lt__(self, other): if self.currency != other.currency: raise ValueError("Cannot compare different currencies") return self.amount < other.amount def __bool__(self): return self.amount != 0 a = Money(10.50) b = Money(5.25) print(f"{a} + {b} = {a + b}") print(f"Equal: {a == b}") print(f"Less than: {b < a}") print(f"Has value: {bool(a)}")
__contains__ enables your classes to integrate seamlessly with Python's operators and built-in functions.
__contains__ with type checking
Implementing __contains__ with proper type handling.
python
# __contains__ with NotImplemented class Vector2D: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): if not isinstance(other, Vector2D): return NotImplemented return Vector2D(self.x + other.x, self.y + other.y) def __mul__(self, scalar): if not isinstance(scalar, (int, float)): return NotImplemented return Vector2D(self.x * scalar, self.y * scalar) def __rmul__(self, scalar): return self.__mul__(scalar) def __repr__(self): return f"Vector2D({self.x}, {self.y})" v = Vector2D(1, 2) print(v + Vector2D(3, 4)) print(v * 3) print(3 * v) # Works because of __rmul__ try: v + 5 # Returns NotImplemented -> TypeError except TypeError as e: print(f"TypeError: {e}")
Always handle type mismatches gracefully by returning NotImplemented for unsupported operations.
Want to try these examples interactively?
Open Intermediate Playground