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 +?
In Python, the `__invert__` method is used to define the behavior of the `~` (bitwise NOT) operator. Just like `__add__` is used for the `+` operator, `__invert__` is called when the `~` operator is used on an instance of a class. Here’s an example of how you might implement `__invert__` in a custom class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class MyClass: def __init__(self, value): self.value = value def __invert__(self): # Define the behavior of the ~ operator return MyClass(~self.value) def __repr__(self): return f"MyClass({self.value})" # Example usage obj = MyClass(5) result = ~obj print(result) # Output: MyClass(-6) |
Testing if the previous output contains the string __invert__
: True
Testing if the previous output contains the string __inv__
: False