Python 内置函数complex详解

yipeiwu_com5年前Python基础

英文文档:

class complex([real[, imag]])

Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like int and float. If both arguments are omitted, returns 0j.

Note

When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.

说明:

  1. 函数功能,返回一个复数。有两个可选参数。

  2. 当两个参数都不提供时,返回复数 0j。

>>> complex()
0j
 

  3. 当第一个参数为字符串时,调用时不能提供第二个参数。此时字符串参数,需是一个能表示复数的字符串,而且加号或者减号左右不能出现空格。

>>> complex('1+2j',2) #第一个参数为字符串,不能接受第二个参数
Traceback (most recent call last):
 File "<pyshell#2>", line 1, in <module>
  complex('1+2j',2)
TypeError: complex() can't take second arg if first is a string

>>> complex('1 + 2j') #不能有空格
Traceback (most recent call last):
 File "<pyshell#3>", line 1, in <module>
  complex('1 + 2j')
ValueError: complex() arg is a malformed string

   4. 当第一个参数为int或者float时,第二个参数可为空,表示虚部为0;如果提供第二个参数,第二个参数也需为int或者float。

>>> complex(2)
(2+0j)
>>> complex(2.1,-3.4)
(2.1-3.4j)
 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

Python对象体系深入分析

Python对象体系深入分析

本文较为详细的分析了了Python的对象体系。分享给大家供大家参考。具体如下: Guido用C语言创造了Python,在Python的世界中一切皆为对象. 一.C视角中的Python对象...

对python3中, print横向输出的方法详解

Python 2 : print打印的时候,如果结尾有逗号,打出来时候不会换行。但是在python3里面就不行了。 Python3 : 3.0的print最后加个参数end=""就可以了...

python3获取当前目录的实现方法

1. 以前的方法 如果是要获得程序运行的当前目录所在位置,那么可以使用os模块的os.getcwd()函数。 如果是要获得当前执行的脚本的所在目录位置,那么需要使用sys模块的sys.p...

opencv3/C++图像像素操作详解

opencv3/C++图像像素操作详解

RGB图像转灰度图 RGB图像转换为灰度图时通常使用: 进行转换,以下尝试通过其他对图像像素操作的方式将RGB图像转换为灰度图像。 #include<opencv2/open...

Python和php通信乱码问题解决方法

即使在urlencode之前str.decode(“cp936″).encode(“utf-8″)做了编码转换也是没用的。后来查询手册查到一个urllib.quote()函数,用此方法成...