GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Python __sub__ Method - Complete Guide Python __sub__ MethodLast modified April 8, 2025
This comprehensive guide explores Python's Basic Definitions
The Key characteristics: it must accept two parameters (self and other), returns the result of subtraction, and can be overridden to customize behavior. It works with both built-in and custom types. Basic __sub__ Implementation
Here's a simple class implementing basic_sub.py
class Number:
def __init__(self, value):
self.value = value
def __sub__(self, other):
if isinstance(other, Number):
return Number(self.value - other.value)
return NotImplemented
a = Number(10)
b = Number(3)
result = a - b
print(result.value) # Output: 7
This example shows how to implement basic subtraction between Number objects.
The
Returning Vector Subtraction
The vector_sub.py
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, other):
if isinstance(other, Vector):
return Vector(self.x - other.x, self.y - other.y)
return NotImplemented
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(5, 7)
v2 = Vector(3, 2)
result = v1 - v2
print(result) # Output: Vector(2, 5)
This Vector class implements component-wise subtraction. The
The Subtracting Different Types
mixed_sub.py
class Currency:
def __init__(self, amount, currency_code):
self.amount = amount
self.currency_code = currency_code
def __sub__(self, other):
if isinstance(other, Currency):
if self.currency_code != other.currency_code:
raise ValueError("Cannot subtract different currencies")
return Currency(self.amount - other.amount, self.currency_code)
elif isinstance(other, (int, float)):
return Currency(self.amount - other, self.currency_code)
return NotImplemented
def __repr__(self):
return f"{self.amount} {self.currency_code}"
usd1 = Currency(100, "USD")
usd2 = Currency(30, "USD")
print(usd1 - usd2) # 70 USD
print(usd1 - 15) # 85 USD
This Currency class allows subtraction between Currency objects of the same type and also supports subtracting numbers directly from the amount. The method includes type checking and currency validation to ensure only meaningful operations are performed. This makes the class more robust. Reverse Subtraction with __rsub__
When the left operand doesn't support subtraction with the right operand,
Python tries the reverse operation using reverse_sub.py
class Temperature:
def __init__(self, value):
self.value = value
def __sub__(self, other):
if isinstance(other, Temperature):
return Temperature(self.value - other.value)
return NotImplemented
def __rsub__(self, other):
if isinstance(other, (int, float)):
return Temperature(other - self.value)
return NotImplemented
def __repr__(self):
return f"{self.value}°C"
temp = Temperature(10)
result1 = temp - Temperature(3) # Uses __sub__
result2 = 20 - temp # Uses __rsub__
print(result1) # 7°C
print(result2) # 10°C
This example shows both normal and reverse subtraction. When Python encounters
Then it tries In-Place Subtraction with __isub__
The inplace_sub.py
class Account:
def __init__(self, balance):
self.balance = balance
def __sub__(self, other):
if isinstance(other, (int, float)):
return Account(self.balance - other)
return NotImplemented
def __isub__(self, other):
if isinstance(other, (int, float)):
self.balance -= other
return self
return NotImplemented
def __repr__(self):
return f"Account(balance={self.balance})"
acc = Account(100)
acc -= 30 # Uses __isub__
print(acc) # Account(balance=70)
The
For mutable objects, implementing Best Practices
Source ReferencesAuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |