Open In App

__invert__ and __abs__ magic functions in Python OOPS

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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)

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.

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)

Output
(155, 105, 55)

__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)

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.

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)

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



Similar Reads

Python | Numpy numpy.ndarray.__invert__()
With the help of Numpy numpy.ndarray.__invert__(), one can invert the elements of an array. We don't have to provide any type of parameter but remember that this method only works for integer values. Syntax: ndarray.__invert__($self, /) Return: ~self Example #1 : In this example we can see that every element in an array is operated on a unary opera
1 min read
Python | Numpy MaskedArray.__abs__
numpy.ma.MaskedArray class is a subclass of ndarray designed to manipulate numerical arrays with missing data. With the help of Numpy MaskedArray.__abs__ operator we can find the absolute value of each and every element in an array. Suppose we have a values 31.74, with the help of MaskedArray.__abs__() it will be converted into 31. Syntax: numpy.Ma
1 min read
NumPy ndarray.__abs__() | Find Absolute Value of Elements in NumPy Array
The ndarray.__abs__() method returns the absolute value of every element in the NumPy array. It is automatically invoked when we use Python's built-in method abs() on a NumPy array. Example C/C++ Code import numpy as np gfg = np.array([1.45, 2.32, 3.98, 4.41, 5.55, 6.12]) print(gfg.__abs__()) Output[ 1 2 3 4 5 6] SyntaxSyntax: ndarray.__abs__() Ret
1 min read
Jupyter Notebook - Cell Magic Functions
In this article, we will cover Cell Magic Functions in Jupyter Notebook we will discuss various functions. But first, we look at what Jupyter Notebook and Cell Magic functions and why we use them. There are a lot of cell magic functions but in this article, we discuss the most commonly used cell magic functions. Jupyter NotebookThe Jupyter Notebook
5 min read
Python OOPS - Aggregation and Composition
In this article, we will compare and highlight the features of aggregation and Composition in Python OOPS. Concept of Inheritance Inheritance is a mechanism that allows us to take all of the properties of another class and apply them to our own. The parent class is the one from which the attributes and functions are derived (also called as Base Cla
5 min read
Shuffle a deck of card with OOPS in Python
The objective is to distribute a deck of cards among two players. The code for the Shuffle Deck of Cards in Python can be used to shuffle the cards. The shuffle method, which is a built-in feature of the random library, is used to mix and randomize the order of the data before printing it. Prerequisites: Python Classes and Objects Steps to Shuffle
3 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles—classes, objects, inheritance, encapsulation, polymorphism, and abstraction—programmers can leverage the full potential of Python's OOP capabilities to design elega
12 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Customize your Python class with Magic or Dunder methods
The magic methods ensure a consistent data model that retains the inherited feature of the built-in class while providing customized class behavior. These methods can enrich the class design and can enhance the readability of the language. So, in this article, we will see how to make use of the magic methods, how it works, and the available magic m
13 min read
__closure__ magic function in Python
Almost everything in Python is an object, similarly function is an object too and all the function objects have a __closure__ attribute. __closure__ is a dunder/magic function i.e. methods having two underscores as prefix and suffix in the method name A closure is a function object that remembers values in enclosing scopes even if they are not pres
1 min read
Practice Tags :