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 +?
The special method (dunder method) for the tilde (`~`) operator in Python is `__invert__`. Just like how `__add__` corresponds to the `+` operator, `__invert__` corresponds to the `~` operator, which performs a bitwise NOT operation. Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class MyNumber: def __init__(self, value): self.value = value def __invert__(self): return MyNumber(~self.value) def __repr__(self): return f"MyNumber({self.value})" num = MyNumber(5) inverted = ~num # This calls num.__invert__() print(inverted) # Output: MyNumber(-6) |
Testing if the previous output contains the string __invert__
: True
Testing if the previous output contains the string __inv__
: False
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 special method for the bitwise NOT operator (`~`) is `__invert__`. Just like `__add__` is used for the `+` operator, `__invert__` is the magic method that gets called when you use the tilde (`~`) operator on an object. For example:
1 2 3 4 5 6 7 8 9 | class MyClass: def __init__(self, value): self.value = value def __invert__(self): return MyClass(-self.value) # Just an example implementation obj = MyClass(5) inverted_obj = ~obj # This calls obj.__invert__() |
Testing if the previous output contains the string __invert__
: True
Testing if the previous output contains the string __inv__
: False