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 Practical Use of Reversed Set Operators in Python?
Reversed set operators in Python are special methods that handle operations when the left operand cannot perform the operation or when the right operand is a subclass. These methods provide fallback mechanisms and enable proper inheritance behavior for custom set-like classes.
Understanding Reversed Operations
When Python evaluates a & b, it first tries a.__and__(b). If this returns NotImplemented or the method doesn't exist, Python tries the reversed operation b.__rand__(a).
class CustomSet:
def __init__(self, items):
self.items = set(items)
def __and__(self, other):
print("Using __and__ method")
return CustomSet(self.items & other.items)
def __rand__(self, other):
print("Using __rand__ method")
return CustomSet(other.items & self.items)
# Example usage
set1 = CustomSet([1, 2, 3])
set2 = CustomSet([2, 3, 4])
result = set1 & set2
Using __and__ method
Subclass Priority Example
Python gives priority to subclass methods even when they appear on the right side of the operation ?
class BaseSet:
def __init__(self, items):
self.items = set(items)
def __and__(self, other):
print("BaseSet __and__")
return BaseSet(self.items & other.items)
def __rand__(self, other):
print("BaseSet __rand__")
return BaseSet(other.items & self.items)
class AdvancedSet(BaseSet):
def __rand__(self, other):
print("AdvancedSet __rand__ (subclass priority)")
return AdvancedSet(other.items & self.items)
# Subclass on right side gets priority
base_set = BaseSet([1, 2, 3])
advanced_set = AdvancedSet([2, 3, 4])
result = base_set & advanced_set
AdvancedSet __rand__ (subclass priority)
NotImplemented Fallback
When the primary method returns NotImplemented, Python automatically tries the reversed operation ?
class SetA:
def __init__(self, items):
self.items = set(items)
def __and__(self, other):
if not hasattr(other, 'items'):
return NotImplemented
return SetA(self.items & other.items)
class SetB:
def __init__(self, items):
self.items = set(items)
def __rand__(self, other):
print("SetB __rand__ called as fallback")
return SetB(other.items & self.items)
# SetA.__and__ returns NotImplemented, so SetB.__rand__ is called
set_a = SetA([1, 2, 3])
set_b = SetB([2, 3, 4])
result = set_a & set_b
SetB __rand__ called as fallback
Common Reversed Set Operators
| Operator | Primary Method | Reversed Method | Purpose |
|---|---|---|---|
| & | __and__ | __rand__ | Intersection |
| | | __or__ | __ror__ | Union |
| ^ | __xor__ | __rxor__ | Symmetric difference |
| - | __sub__ | __rsub__ | Difference |
Practical Implementation
class SmartSet:
def __init__(self, items):
self.items = set(items)
self.name = "SmartSet"
def __or__(self, other):
if hasattr(other, 'items'):
return SmartSet(self.items | other.items)
return NotImplemented
def __ror__(self, other):
if hasattr(other, 'items'):
result = SmartSet(other.items | self.items)
result.name = "Merged from reversed operation"
return result
return NotImplemented
def __str__(self):
return f"{self.name}: {self.items}"
# Test with different scenarios
smart1 = SmartSet([1, 2])
smart2 = SmartSet([3, 4])
result = smart1 | smart2
print(result)
SmartSet: {1, 2, 3, 4}
Conclusion
Reversed set operators provide essential fallback mechanisms and enable proper inheritance behavior in custom classes. They ensure operations work correctly when the primary method fails or when dealing with subclass priority, making your custom set-like classes more robust and interoperable.
