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.
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)
Output
5.0
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.
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)
Output
3.7416573867739413
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
__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