__contains__ Powers the in Operator
Implement __contains__ on a class so membership checks run your logic; the fallback when missing is __iter__, not __len__.
Code
class Inventory:
def __init__(self, items):
self.items = set(items)
# __contains__ 让 in 走自定义成员判定
def __contains__(self, item):
return item in self.items
def __len__(self):
return len(self.items)
inv = Inventory(["sword", "potion"])
print("sword" in inv, "shield" in inv)
print(len(inv))Output
Captured from a sandboxed run of this snippet in the build pipeline.
True False
2How it works
All of the logic lives in the class Inventory and the functions __init__, __contains__ and __len__.
Watch out for
- Zero packages pulled in — the runtime ships every API this code touches.
Using it
Signature: def __init__(self, items)
The run emits 1 labeled section — sword — one per step.
Key statements
def __contains__(self, item):
return item in self.items
def __init__(self, items):
self.items = set(items)
def __len__(self):
return len(self.items)
Interactive Tools for This Topic
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `__init__`, `__contains__`, `__len__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.