Solved: Python __sub__ magic method

The __sub__ magic method in Python is used to call a function that takes two arguments, but the first argument is interpreted as a subclass of the second argument’s class. This can lead to unexpected behavior if the subclass doesn’t implement the __sub__ magic method.


The __sub__ magic method is used to implement the subtraction operator for objects. It is called when the - operator is used on two objects of the same type. The __sub__ method should return the result of the subtraction operation.

For example, if we have a class that represents a complex number, we could define the __sub__ method like this:

class ComplexNumber: def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __sub__(self, other): return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)

Now we can use the - operator on two ComplexNumber objects:

c1 = ComplexNumber(1, 2) c2 = ComplexNumber(3, 4) c3 = c1 - c2 print(c3) # Prints ComplexNumber(real=-2, imaginary=-2)

What is Magic Method

In Python, magic method is a special type of function that allows you to call a function without specifying its name. This is done by prefixing the function’s name with an ampersand (&).

List of Magic methodes

There are many different ways to do magic in Python. Here are a few:

1. import random
2. import time
3. from math import sqrt, pi
4. from datetime import date, time
5. from operator import add, subtract, multiply, divide
6. from functools import partial
7. from collections import deque

Related posts:

Leave a Comment