__abs__Easy Examples

Called by abs(); returns the absolute value

Implementing __abs__

Basic implementation of __abs__ in a class.

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

obj = Example()
print(obj)

__abs__ called by abs(); returns the absolute value. Implementing it lets you customize how Python interacts with your objects.

__abs__ in action

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

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

    def __abs__(self):
        print(f"__abs__ was called!")
        return self

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

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

Want to try these examples interactively?

Open Easy Playground