__sub__ — Easy Examples
Defines behavior for the - subtraction operator
Implementing __sub__
Basic implementation of __sub__ in a class.
python
class Example: def __sub__(self): return "Example __sub__" obj = Example() print(obj)
__sub__ defines behavior for the - subtraction operator. Implementing it lets you customize how Python interacts with your objects.
__sub__ in action
Seeing __sub__ called by Python's built-in operations.
python
# How Python calls __sub__ automatically class Demo: def __init__(self, value): self.value = value def __sub__(self, other): print(f"__sub__ was called!") return self d = Demo(42) # This triggers __sub__: result = d - Demo(1)
Python automatically calls __sub__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground