__truediv__Easy Examples

Defines behavior for the / true division operator

Implementing __truediv__

Basic implementation of __truediv__ in a class.

python
class Example:
    def __truediv__(self):
        return "Example __truediv__"

obj = Example()
print(obj)

__truediv__ defines behavior for the / true division operator. Implementing it lets you customize how Python interacts with your objects.

__truediv__ in action

Seeing __truediv__ called by Python's built-in operations.

python
# How Python calls __truediv__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __truediv__(self, other):
        print(f"__truediv__ was called!")
        return self

d = Demo(42)
# This triggers __truediv__:
print(d)

Python automatically calls __truediv__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground