__int__Easy Examples

Called by int(); returns an integer representation

Implementing __int__

Basic implementation of __int__ in a class.

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

obj = Example()
print(obj)

__int__ called by int(); returns an integer representation. Implementing it lets you customize how Python interacts with your objects.

__int__ in action

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

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

    def __int__(self):
        print(f"__int__ was called!")
        return self.value

d = Demo(42)
# This triggers __int__:
print(int(d))

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

Want to try these examples interactively?

Open Easy Playground