__div__() magic method overrides the division operation for a custom object in Python 2.
In Python 3, it was replaced by the
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 expression
x / y, Python attempts to call
- The Python
__floordiv__()method implements the integer division operation
//called floor division. For example to evaluate the expression
x // y, Python attempts to call
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. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, 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.