在python中复数的处理相对简单,定义一个复数通常来说有两种方式,代码如下:
NB(注意): ​​​#​​ 后面的部分表示输出结果。

class Debug:
def complexDefine(self):
# method 1
x = 1j
print(x) # 1j
print(type(x)) # <class 'complex'>

# method 2
x1 = complex(1, 2)
print(x1) # (1+2j)
print(type(x1)) # <class 'complex'>

# debug
main = Debug()
main.complexDefine()

我们可以看到可以直接使用j来创建一个虚数,也可以使用关键字​​complex​​​来创建一个虚数,并且虚数同时拥有实部与虚部时,实部在前,虚部在后,如定义方法二中的​​(1+2j)​​​,其中​​1​​​为实部,​​2​​​为虚部。
此外在python还存在一个内置模块​​​cmath​​可以用来处理复数运算,代码如下:

class Debug:
def complexDefine(self):
x = -1
x1 = cmath.sqrt(x)
print(x1) # 1j

# debug
main = Debug()
main.complexDefine()

那么如何获取复数的实部和虚部呢?代码如下:

class Debug:
@staticmethod
def complexDefine():
x = complex(1, 2)
x_real = x.real
x_image = x.imag
print('The real part of this complex number is:')
print(x_real)
print('The imaginary part of this complex number is:')
print(x_image)


main = Debug()
main.complexDefine()
"""
The real part of this complex number is:
1.0
The imaginary part of this complex number is:
2.0
"""

由此我们可以知道,可以通过​​.real​​​和​​.image​​来分别获取一个复数的实部与虚部部分。