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