What is bitwise operator overloading in Python?
Overview
Operator overloading means giving extended meaning to an operator beyond its predefined meaning. It provides an additional ability for any operator to react depending upon the scenario.
For instance, the + operator can be used to add two integer values to concatenate two or more strings. Hence, it is called operator overloading because, in a standard string library, the + operator is overloaded for concatenation.
Let's take a look at bitwise operator overloading in detail.
The AND operator
Let's look at an example of the bitwise AND operator's overloading.
# Python program to demonstrate# operator overloadingclass Test():def __init__(self, value):self.value = value# magic function to perform logical ANDdef __and__(self, obj):print("Overloaded AND Operator")if isinstance(obj, Test):return self.value & obj.valueelse:raise ValueError("Must be an instance of Test class")# Driver's codeif __name__ == "__main__":a = Test(9) # 0000 1001b = Test(12) # 0000 1100print(a & b)
Explanation
- Lines 3–12: We create a
Testclass. It has a magic method__and__()to perform the bit-wise logicalANDoperation. - Lines 9–10:
isinstance(obj, Test)will check whether the argument objectobjis of theTest.classtype or not. We then perform the bitwise logicalAND - Line 12: When the argument is of a different type, it returns a value error.
- Lines 15–18: We create two objects of the
Testclass,aandb. We then use the above-created function to perform logicalAND.
The OR operator
Below, we have an example of bitwise OR operator's overloading.
# Python program to demonstrate# operator overloadingclass Test():def __init__(self, value):self.value = value# magic function to perform logical ORdef __or__(self, obj):print("Overloaded OR Operator")if isinstance(obj, Test):return self.value | obj.valueelse:raise ValueError("Must be an instance of Test class")# Driver's codeif __name__ == "__main__":a = Test(9) # 0000 1001b = Test(12) # 0000 1100print(a | b)
Explanation
- Lines 3–12: We create a
Testclass. It has the method__or__()to perform the bitwise logicalORoperation. - Lines 9–10:
isinstance(obj, Test)will check whether the argument objectobjis ofTestclass type or not. We then perform the bitwise logicalOR. - Line 12: When the argument is of a different type, it will return a value error.
- Lines 15–18: We create two objects of
Testclass,aandb. Finally, we use the above-created function to perform the logicalOR.
The XOR operator
Below, we see an example of bitwise XOR operator's overloading:
# Python program to demonstrate# operator overloadingclass Test():def __init__(self, value):self.value = value# magic function to perform logical XORdef __xor__(self, obj):print("Overloaded XOR Operator")if isinstance(obj, Test):return self.value ^ obj.valueelse:raise ValueError("Must be an instance of Test class")# Driver's codeif __name__ == "__main__":a = Test(9) # 0000 1001b = Test(12)# 0000 1100print(a ^ b)
Explanation
- Lines 3–12: We create a
Testclass. It has a method__xor__()to perform the bitwise logicalXORoperation. - Lines 9–10:
isinstance(obj, Test)will check whether the argument objectobjis of theTest.classtype or not. It then performs the bitwise logicalXOR. - Line 12:
When the argument is of a different type, it returns a value error.When argument is of different type.
- Lines 15–18: We create two objects of the
Testclass, that is,a=9andb=12. Finally, using the above created function, we perform the logicalXOR.
The NOT operator
Below, we see an example of bitwise NOT operator's overloading:
# Python program to demonstrate# operator overloadingclass Test():def __init__(self, value):self.value = value# magic method for NOTdef __invert__(self):print("Overloaded NOT Operator")if isinstance(self, Test):return ~self.valueelse:raise ValueError("Must be an instance of Test class")# Driver's codeif __name__ == "__main__":a = Test(9) # 0000 1001print(~a)
Explanation
- Lines 3–12: We create a
Testclass withvalueas a field. It has a magic method__invert__()to perform the bitwise logicalNOT. - Lines 9–10:
isinstance(obj, Test)will check whether the argument objectobjis ofTest.classtype or not. We then perform the bitwise logicalNOT. - Line 12:
When the argument is of a different type, it returns a value error message.When argument is of different type.
- Lines 14–16: We create an object of the
Testclassa. Finally, using the function we created above, we perform the logicalNOT.
Left shift <<
Below, we see an example of the bitwise left shift (<<) operator's overloading:
# Python program to demonstrate# operator overloadingclass Test():def __init__(self, value):self.value = value# Left shift of bitsdef __lshift__(self, obj):print("Overloaded LEFT SHIFT Operator")if isinstance(obj, Test):return self.value << obj.valueelse:raise ValueError("Must be an instance of Test class")# Driver's codeif __name__ == "__main__":a = Test(2) # 0000 0010b = Test(3) # 0000 0011print(a << b)
Explanation
- Lines 3–12: We create a
Testclass withvalueas a field. It has a magic method__lshift__()to perform the bitwise left shift. - Lines 9–10:
isinstance(obj, Test)will check whether the argument objectobjis ofTest.classtype or not. We then perform the bitwise logical left shift. - Line 12: When the argument is of a different type, it returns a value error message.
- Lines 14–17: We create two instances of the
Testclass typesa=2andb=3. Finally, using the function we created above, we perform the logical left shift.
Right shift >>
Below, we see an example of the bitwise right shift >> operator's overloading:
# Python program to demonstrate# operator overloadingclass Test():def __init__(self, value):self.value = value# right shiftdef __rshift__(self, obj):print("Overloaded RIGHT SHIFT Operator")if isinstance(obj, Test):return self.value >> obj.valueelse:raise ValueError("Must be an instance of Test class")# Driver's codeif __name__ == "__main__":a = Test(2) # 0000 0010b = Test(3) # 0000 0011print(a >> b)
Explanation
- Lines 3–12: We create a
Testclass that contains a single member field. It has a magic method__rshift__()to perform bitwise's right shift. - Lines 9–10:
isinstance(obj, Test)will check whether the argument objectobjis of theTest.classtype or not. We then perform the bitwise logical right shift. - Line 12: When the argument is of a different type, it returns a value error message.
- Lines 14–17: We create two instances of
Testclass types.a=2andb=3. Finally, we use the function we created above to perform the bitwise right shift.