Model complex-valued data
Represent values with both real and imaginary components, such as signals or phasors.
Python · Class
complex() converts a string or number to a complex number, or constructs one from real and imaginary parts. It also supports documented numeric conversion protocols for general objects.
The built-in complex type converts one string or number into a complex number, or combines real and imaginary numeric arguments. With two arguments, the result represents the supplied components; with one object, conversion can use its numeric conversion protocol.
class complex(real=0, imag=0)| Name | Type | Description |
|---|---|---|
real | object | A string or number to convert, or the real component when constructing from two values. |
imag | object | The imaginary component; when supplied, it must be numeric and cannot be a string. |
A complex number.
z = complex(3, 4)
print(z.real, z.imag)
print(complex("-1+2j"))Creates a complex value from real and imaginary parts, then parses a string representation.
Represent values with both real and imaginary components, such as signals or phasors.
Turn user or configuration text such as "-1+2j" into a complex value.
Convert compatible custom numeric objects through Python's numeric protocols.
complex() accepts either one string or numeric value, or real and imaginary numeric arguments. Two arguments produce a value representing those components.
Follow-up: What happens for a custom object? The conversion delegates to __complex__(), then can fall back to __float__() and __index__().
For real arguments real and imag, complex(real, imag) represents real + imag·1j. A single string is interpreted as a complex-number representation.
Follow-up: Can a string be used as the second argument? No; the second parameter cannot be a string.
For a general object, complex(x) first delegates to x.__complex__(). If that is unavailable, conversion falls back to __float__(), then __index__().
Follow-up: What if two arguments are supplied? Each may be any numeric type, including complex, with the documented component formulas applied.
float()int()numbers.Complex__complex__()__float__()__index__()