The Python __div__()
magic method overrides the division operation for a custom object in Python 2.
In Python 3, it was replaced by the __truediv__()
for a / b
and __floordiv__()
dunder methods for a // b
.
- The Python
__truediv__()
method is called to implement the normal division operation/
called true division. For example to evaluate the expressionx / y
, Python attempts to callx.__truediv__(y)
. - The Python
__floordiv__()
method implements the integer division operation//
called floor division. For example to evaluate the expressionx // y
, Python attempts to callx.__floordiv__(y)
.
If the method is not implemented, Python first attempts to call __rtruediv__
or __rfloordiv__
on the right operand and if this isnβt implemented either, it raises a TypeError
.
TypeError: unsupported operand type(s) for /
In the following example, you try to override the division operator on the custom object Data by using the __div__()
magic method.
# Python 3 - WRONG: class Data: def __div__(self, other): return 42.42 x = Data() y = Data() print(x / y)
However, this doesn’t work for Python 3—you obtain the following output error message:
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 9, in <module> print(x / y) TypeError: unsupported operand type(s) for /: 'Data' and 'Data'
To fix this issue, override the __truediv__()
magic method for Python 3 instead of the __div__()
magic method for Python 2 to define the true division operator x / y
.
You can see how it’s done in the following code example (see highlighted lines):
class Data: def __truediv__(self, other): return 42.42 x = Data() y = Data() print(x / y) # 42.42
Explainer Video Division Operators
You can also check out my explainer video where Iβll give you a deep dive on the integer and true division operators and how to use them for various data types. Click to watch:

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.