__complex__ — Easy Examples
Called by complex(); returns a complex number representation
Implementing __complex__
Basic implementation of __complex__ in a class.
python
class Example: def __complex__(self): return "Example __complex__" obj = Example() print(obj)
__complex__ called by complex(); returns a complex number representation. Implementing it lets you customize how Python interacts with your objects.
__complex__ in action
Seeing __complex__ called by Python's built-in operations.
python
# How Python calls __complex__ automatically class Demo: def __init__(self, value): self.value = value def __complex__(self): print(f"__complex__ was called!") return self d = Demo(42) # This triggers __complex__: print(d)
Python automatically calls __complex__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground