__and__ — Easy Examples
Defines behavior for the & bitwise AND operator
Implementing __and__
Basic implementation of __and__ in a class.
python
class Example: def __and__(self): return "Example __and__" obj = Example() print(obj)
__and__ defines behavior for the & bitwise and operator. Implementing it lets you customize how Python interacts with your objects.
__and__ in action
Seeing __and__ called by Python's built-in operations.
python
# How Python calls __and__ automatically class Demo: def __init__(self, value): self.value = value def __and__(self, other): print(f"__and__ was called!") return self d = Demo(42) # This triggers __and__: print(d)
Python automatically calls __and__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground