__invert__ and __abs__ magic functions in Python OOPS
Last Updated :
20 Mar, 2024
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.
__invert__() Magic Function in Python
The __invert__
magic function is used to define the behavior of the bitwise NOT operation (~
). When this method is implemented in a class, it is called whenever the object is used with the bitwise NOT operator. This allows developers to customize how instances of a class respond to bitwise NOT operations.
Syntax of __invert__() Magic Function
class MyClass:
def __invert__(self):
# Custom implementation for bitwise NOT operation
# Return the result of the operation
pass
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`.
Python3
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)
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.
Python3
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)
__abs__() Magic Function in Python
The __abs__
magic function is related to the absolute value of an object. When this method is defined in a class, it is called when the abs()
function is applied to an instance of that class. This enables developers to specify how objects of a particular class should handle absolute value computations.
Syntax of __abs__() Magic Function
class MyClass:
def __abs__(self):
# Custom implementation for bitwise NOT operation
# Return the result of the operation
pass
Python __abs__() Magic Function Examples
Below are some of the examples of __abs__() magic function in Python:
Example 1: Absolute Value of a ComplexNumber class
In this example, the `ComplexNumber` class represents complex numbers, and its `__abs__` method customizes the absolute value computation. The example creates a complex number with real part 3 and imaginary part 4, calculates its absolute value using the `abs()` function.
Python3
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __abs__(self):
# Custom implementation for absolute value computation
return (self.real**2 + self.imag**2)**0.5
# Example usage:
complex_num = ComplexNumber(3, 4)
absolute_value = abs(complex_num)
print(absolute_value)
Example 2: Absolute Value of Vector class
In this example, In below code the`Vector` class represents mathematical vectors, and its `__abs__` method customizes the computation of the vector's magnitude or absolute value. The example creates a vector with components [1, 2, 3], calculates its magnitude using the `abs()` function.
Python3
class Vector:
def __init__(self, components):
self.components = components
def __abs__(self):
# Custom implementation for absolute value computation
return sum(component**2 for component in self.components)**0.5
# Example usage:
vector = Vector([1, 2, 3])
magnitude = abs(vector)
print(magnitude)
Conclusion
In conclusion, the __invert__
and __abs__
magic functions provide a way to customize the behavior of objects in Python when subjected to bitwise NOT and absolute value operations, respectively. Incorporating these methods into classes empowers developers to tailor the behavior of their objects, enhancing the flexibility and expressiveness of their code
Similar Reads
Python - Tuple elements inversions Sometimes, while programming, we have a problem in which we might need to perform certain bitwise operations among tuple elements. This is an essential utility as we come across bitwise operations many times. Letâs discuss certain ways in which this task can be performed. Method #1 : Using map() + l
3 min read
Python - Change the signs of elements of tuples in a list Given a dual Tuple list, the task is to write a python program to convert second element to negative magnitude of each tuple and first element to positive magnitude of each tuple. Input : test_list = [(3, -1), (-4, -3), (1, 3), (-2, 5), (-4, 2), (-9, -3)] Output : [(3, -1), (4, -3), (1, -3), (2, -5)
3 min read
Python - Convert Dictionary values to Absolute Magnitude Given a dictionary, convert its values to absolute. Input : test_dict = {"Gfg" : -5, "is" : -7, "Best" : -2} Output : {"Gfg" : 5, "is" : 7, "Best" : 2} Explanation : All negative elements changed to positive with same magnitude Input : test_dict = {"Gfg" : -8, "is" : 7, "Best" : -2} Output : {"Gfg"
7 min read
Python program to print negative numbers in a list In Python, itâs often necessary to find and print negative numbers from a list. In this article we will explore various approches to print negative numbers in a list. The most basic method for printing negative numbers is to use a for loop to iterate through the list and check each element.Pythona =
2 min read
Python List Inversions Sometimes, while programming, we have a problem in which we might need to perform certain bitwise operations among list elements. This is an essential utility as we come across bitwise operations many times. Letâs discuss certain ways in which this task can be performed. List Inversions using map()
4 min read