__float__Easy Examples

Called by float(); returns a float representation

Implementing __float__

Basic implementation of __float__ in a class.

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

obj = Example()
print(obj)

__float__ called by float(); returns a float representation. Implementing it lets you customize how Python interacts with your objects.

__float__ in action

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

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

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

d = Demo(42)
# This triggers __float__:
print(float(d))

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

Want to try these examples interactively?

Open Easy Playground