In python what __thing__ do I use for ~, kind of like how __add__ is for +?
In python what __thing__ do I use for ~, kind of like how __add__ is for +?
That would be the `__invert__` method. The `~` operator in Python performs bitwise inversion (or bitwise NOT). When you use the `~` operator on an object, Python looks for and calls its `__invert__` method. Here's a quick example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class MyNumber: def __init__(self, value): self.value = value def __invert__(self): print(f"Calling __invert__ on {self.value}") # Example: return the negative value for demonstration # For integers, ~x is equivalent to -(x+1) return -self.value - 1 def __repr__(self): return f"MyNumber({self.value})" num = MyNumber(5) inverted_num = ~num # This calls num.__invert__() print(f"Original: {num}") print(f"Inverted: {inverted_num}") # For standard integers: print(f"~5 = {~5}") |
1 2 3 4 | Calling __invert__ on 5 Original: MyNumber(5) Inverted: -6 ~5 = -6 |
Testing if the previous output contains the string __invert__
: True
Testing if the previous output contains the string __inv__
: False