Python Programming - Overloading Bitwise Operators

Python Programming – Overloading Bitwise Operators

As we know that Python contains a rich set of operators. The bitwise operators can also be overloaded like arithmetic operators. Here in this section, we learn to overload bitwise and operator (‘&’)- The programming illustration to overload bitwise and (&) operator is given in Code 12.3. As we know that the bitwise and (&) works at the bit level and return true (1) only if both the bits are true (1), otherwise it returns false (0). In this program, we see that a Number class is created, which contains only one data member num. the__init__() method initialize the value of this variable for two objects n1 and n2.

In order to overload, the bitwise and (&) operator the invocation is made as nl&n2, where n1 and n2 are the objects of class Number and the result is assigned to the third object n3. The invocation nl&n2 expands as n1. and (n2), where and Q is the built-in Python function for overloading bitwise and operator. In the definition part of this function, n1 represents the calling object that is self and n2 represents the object as argument i.e., obj. The computation is performed by using the dot (.) operator with these two objects self and obj and the bitwise and operator &. The result is returned by typecasting with the class data type Number. The result is received by the object n3 and displayed by calling the n3.display() function. The computation of bitwise and (&) operator over two values 14 and 28 results in 12 as shown in the output.

Code: 12,3. Illustration of overloading bitwise & operator

#illustration of Bitwise ‘&’ operator overloading

class Number:
‘A Number class’
def__init__(self, num):
self.num = num

def__and_(self, obj):
num = self.num&obj.num
retum(Number(num))

def display(self):
print(self.num)

n1=Number(14)
n2=Number(28)
n3=nl&n2
n3 .display()

Output

12

Similarly, other bitwise operators can be overloaded, the Python built-in functions for them are given in Table 12.2.

Operator Expression Built-in function
Bitwise AND cl &c2 C1 and (c2)
Bitwise OR cl | c2 C1 or (c2)
Bitwise XOR cl∧c2 C1 xor (c2)
Bitwise NOT ~cl C1 invert (c2)
Bitwise Left Shift cl « c2 C1 lshift (c2)
Bitwise Right Shift cl »c2 C1 rsshift (c2)
Note: cl and c2 are objects.

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *