Python operator overloading using bitwise operators, to define the behavior of bitwise operations for custom classes. By implementing special methods such as __and__
, __or__
, __xor__
, __lshift__
, __rshift__
, and __invert__
, you can customize how bitwise operations work with your objects.
Here’s an example that demonstrates overloading bitwise operators in Python:
class Number: def __init__(self, value): self.value = value def __and__(self, other): if isinstance(other, Number): return Number(self.value & other.value) else: raise TypeError("Unsupported operand type for bitwise and.") def __or__(self, other): if isinstance(other, Number): return Number(self.value | other.value) else: raise TypeError("Unsupported operand type for bitwise or.") def __xor__(self, other): if isinstance(other, Number): return Number(self.value ^ other.value) else: raise TypeError("Unsupported operand type for bitwise xor.") def __lshift__(self, other): if isinstance(other, int): return Number(self.value << other) else: raise TypeError("Unsupported operand type for left shift.") def __rshift__(self, other): if isinstance(other, int): return Number(self.value >> other) else: raise TypeError("Unsupported operand type for right shift.") def __invert__(self): return Number(~self.value) # Create two Number objects num1 = Number(5) num2 = Number(3) # Perform bitwise AND operation result_and = num1 & num2 print(result_and.value) # Output: 1 # Perform bitwise OR operation result_or = num1 | num2 print(result_or.value) # Output: 7 # Perform bitwise XOR operation result_xor = num1 ^ num2 print(result_xor.value) # Output: 6 # Perform left shift operation result_lshift = num1 << 2 print(result_lshift.value) # Output: 20 # Perform right shift operation result_rshift = num1 >> 1 print(result_rshift.value) # Output: 2 # Perform bitwise inversion result_invert = ~num1 print(result_invert.value) # Output: -6
In the example above, the Number
class overloads the bitwise operators &
(and), |
(or), ^
(xor), <<
(left shift), >>
(right shift), and ~
(invert). The respective dunder methods are implemented to handle these operations for Number
objects.
By implementing these methods, we can perform bitwise operations between Number
objects or between a Number
object and an integer. The behavior of these operations is defined based on the logic provided in the respective dunder methods.
Note that in the example, the value
attribute of the Number
class represents the underlying integer value for the bitwise operations.
By overloading the bitwise operators, you can define custom behavior for bitwise operations in your custom classes, allowing for more meaningful and intuitive bitwise calculations.