Python __invert__() Magic Function Examples
Below are some of the examples by which we can understand about Python __invert__() Function:
Example 1: Customize Bitwise NOT for BinaryNumber Class
In this example, in below code `BinaryNumber` class represents binary numbers, and its `__invert__` method customizes the bitwise NOT operation. When applied to an instance, such as `binary_num`, the result is an inverted binary number, demonstrated by `inverted_num.value`.
class BinaryNumber:
def __init__(self, value):
self.value = value
def __invert__(self):
# Custom implementation for bitwise NOT operation
inverted_value = ~self.value
return BinaryNumber(inverted_value)
# Example usage:
binary_num = BinaryNumber(5)
inverted_num = ~binary_num
print(inverted_num.value)
Output
-6
Example 2: Implement __invert__ For Color Class
In this example, In below code `Color` class represents RGB colors, and its `__invert__` method customizes the bitwise NOT operation on each RGB component. The example creates an original color with RGB values (100, 150, 200), applies bitwise NOT to each component.
class Color:
def __init__(self, rgb):
self.rgb = rgb
def __invert__(self):
# Custom implementation for bitwise NOT operation
inverted_rgb = tuple(255 - value for value in self.rgb)
return Color(inverted_rgb)
# Example usage:
original_color = Color((100, 150, 200))
inverted_color = ~original_color
print(inverted_color.rgb)
Output
(155, 105, 55)
__invert__ and __abs__ magic functions in Python OOPS
The __invert__
and __abs__
magic methods are used for implementing unary operators in Python. In this article, we will see the concept of __invert__ and __abs__ magic functions in Python.
Contact Us