Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is operator binding in Python?
Operator binding in Python refers to how the Python interpreter determines which object's special method to call when evaluating binary operators like ==, +, <, etc.
How Operator Binding Works
When Python encounters a binary expression, it follows a specific binding protocol to determine which object handles the operation.
Example with Equality Operator
For expressions like ?
a == b
Python follows this binding sequence:
Step 1: First, the Python interpreter looks up the __eq__() method on the left operand (object a). If it finds that method, it executes a.__eq__(b).
Step 2: If a.__eq__(b) returns NotImplemented, Python tries the reverse operation by calling ?
b.__eq__(a)
Practical Example
Let's see operator binding in action with a custom class ?
class Number:
def __init__(self, value):
self.value = value
def __eq__(self, other):
print(f"Calling Number.__eq__({self.value}, {other})")
if isinstance(other, Number):
return self.value == other.value
return NotImplemented
class SpecialNumber:
def __init__(self, value):
self.value = value
def __eq__(self, other):
print(f"Calling SpecialNumber.__eq__({self.value}, {other})")
return self.value == other
# Testing operator binding
num1 = Number(5)
special = SpecialNumber(5)
# This will try num1.__eq__(special) first
result = num1 == special
print(f"Result: {result}")
Calling Number.__eq__(5, <__main__.SpecialNumber object at 0x...>) Calling SpecialNumber.__eq__(5, <__main__.Number object at 0x...>) Result: True
Binding Order for Other Operators
The same binding principle applies to other binary operators ?
class Demo:
def __init__(self, value):
self.value = value
def __add__(self, other):
print(f"Left operand handles addition: {self.value} + {other}")
return NotImplemented
def __radd__(self, other):
print(f"Right operand handles addition: {other} + {self.value}")
return other + self.value
obj = Demo(10)
# When 5 + obj is called, obj.__radd__(5) is used
result = 5 + obj
print(f"Final result: {result}")
Right operand handles addition: 5 + 10 Final result: 15
Conclusion
Operator binding in Python follows a left-to-right precedence where the left operand's special method is tried first. If it returns NotImplemented, Python attempts the reverse operation on the right operand, ensuring flexible operator overloading.
