内置类型

以下章节描述解释器内置的标准类型。

主要内置类型,包括:数值、序列、映射、类、实例及异常。

某些集合类是可变的。添加、减去或原位重新排列其成员且不返回特定项的方法,从不返回集合实例本身而是 None .

某些操作支持几种对象类型;尤其,实际上所有对象都可以进行相等比较、测试真值及转换为字符串 (采用 repr() 函数或稍微不同的 str() 函数)。隐式使用后一函数当对象写入通过 print() 函数。

真值测试

可以测试任何对象的真值,对于用于 if or while 条件或作为以下布尔运算的操作数。

默认情况下,对象被认为是 True ,除非其类定义的 __bool__() 方法返回 False __len__() 方法返回 0,当调用对象时。 [ 1 ] 这里是被认为是 False 的大多数内置对象:

  • 定义为 False 的常量: None and False

  • 任何数值类型的零: 0 , 0.0 , 0j , Decimal(0) , Fraction(0, 1)

  • 空序列和集合: '' , () , [] , {} , set() , range(0)

拥有 Boolean (布尔) 结果的运算和内置函数始终返回 0 or False 对于 false 和 1 or True 对于 true,除非另有说明 (重要例外:布尔运算 or and and 始终返回它们的操作数之一)。

布尔运算 — and , or , not

这些是布尔运算,按优先级升序排序:

操作

结果

注意事项

x or y

if x 为 true,则 x ,否则 y

(1)

x and y

if x 为 False,那么 x ,否则 y

(2)

not x

if x 为 False,那么 True ,否则 False

(3)

注意事项:

  1. 这是短路运算符,所以它只评估第 2 自变量,若第 1 自变量为 False。

  2. 这是短路运算符,所以它只评估第 2 自变量,若第 1 自变量为 True。

  3. not 拥有比非布尔运算符更低的优先级,所以 not a == b 被解释成 not (a == b) ,和 a == not b 是句法错误。

比较

Python 中存在 8 种比较操作。它们拥有相同优先级 (高于布尔运算)。比较可以任意连锁;例如, x < y <= z 相当于 x < y and y <= z ,除了 y 只评估 1 次 (但在 2 种情况下, z 根本不评估当 x < y 被发现为 False)。

此表汇总了比较操作:

操作

含义

<

严格小于

<=

小于等于

>

严格大于

>=

大于等于

==

equal

!=

不等于

is

对象身份

is not

否定对象身份

Objects of different types, except different numeric types, never compare equal. The == operator is always defined but for some object types (for example, class objects) is equivalent to is < , <= , > and >= operators are only defined where they make sense; for example, they raise a TypeError exception when one of the arguments is a complex number.

Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__() 方法。

Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods __lt__() , __le__() , __gt__() ,和 __ge__() (一般而言, __lt__() and __eq__() are sufficient, if you want the conventional meanings of the comparison operators).

行为对于 is and is not 操作符无法定制;还可以将它们应用于任何 2 对象,且从不引发异常。

另外,具有相同句法优先级的 2 操作 in and not in ,的支持是通过类型 iterable 或实现 __contains__() 方法。

数值类型 — int , float , complex

有 3 种截然不同的数值类型: integers , floating-point numbers ,和 复数 . In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating-point numbers are usually implemented using double in C; information about the precision and internal representation of floating-point numbers for the machine on which your program is running is available in sys.float_info . Complex numbers have a real and imaginary part, which are each a floating-point number. To extract these parts from a complex number z ,使用 z.real and z.imag . (The standard library includes the additional numeric types fractions.Fraction , for rationals, and decimal.Decimal , for floating-point numbers with user-definable precision.)

Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including hex, octal and binary numbers) yield integers. Numeric literals containing a decimal point or an exponent sign yield floating-point numbers. Appending 'j' or 'J' to a numeric literal yields an imaginary number (a complex number with a zero real part) which you can add to an integer or float to get a complex number with real and imaginary parts.

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex. A comparison between numbers of different types behaves as though the exact values of those numbers were being compared. [ 2 ]

构造函数 int() , float() ,和 complex() 可用于产生特定类型的数字。

All numeric types (except complex) support the following operations (for priorities of the operations, see 运算符优先级 ):

操作

结果

注意事项

完整文档编制

x + y

和对于 x and y

x - y

difference of x and y

x * y

乘积对于 x and y

x / y

quotient of x and y

x // y

floored quotient of x and y

(1)(2)

x % y

余数对于 x / y

(2)

-x

x negated

+x

x unchanged

abs(x)

absolute value or magnitude of x

abs()

int(x)

x 被转换成整数

(3)(6)

int()

float(x)

x 被转换成浮点数

(4)(6)

float()

complex(re, im)

a complex number with real part re , imaginary part im . im defaults to zero.

(6)

complex()

c.conjugate()

conjugate of the complex number c

divmod(x, y)

(x // y, x % y)

(2)

divmod()

pow(x, y)

x 到幂 y

(5)

pow()

x ** y

x 到幂 y

(5)

注意事项:

  1. Also referred to as integer division. For operands of type int , the result has type int . For operands of type float , the result has type float . In general, the result is a whole integer, though the result’s type is not necessarily int . The result is always rounded towards minus infinity: 1//2 is 0 , (-1)//2 is -1 , 1//(-2) is -1 ,和 (-1)//(-2) is 0 .

  2. 不适用于复数。相反,转换为浮点数使用 abs() 若合适。

  3. Conversion from float to int truncates, discarding the fractional part. See functions math.floor() and math.ceil() for alternative conversions.

  4. float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.

  5. Python 定义 pow(0, 0) and 0 ** 0 1 , as is common for programming languages.

  6. The numeric literals accepted include the digits 0 to 9 or any Unicode equivalent (code points with the Nd 特性)。

    the Unicode Standard for a complete list of code points with the Nd 特性。

所有 numbers.Real 类型 ( int and float ) 还包括以下操作:

操作

结果

math.trunc(x)

x truncated to Integral

round(x[, n])

x 四舍五入到 n digits, rounding half to even. If n is omitted, it defaults to 0.

math.floor(x)

the greatest Integral <= x

math.ceil(x)

the least Integral >= x

其它数值运算,见 math and cmath 模块。

整数类型的按位运算

Bitwise operations only make sense for integers. The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits.

The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation ~ 具有相同优先级,如同其它一元数值运算 ( + and - ).

此表按优先级升序排序,列出按位运算:

操作

结果

注意事项

x | y

bitwise or of x and y

(4)

x ^ y

bitwise exclusive or of x and y

(4)

x & y

bitwise and of x and y

(4)

x << n

x shifted left by n bits

(1)(2)

x >> n

x shifted right by n bits

(1)(3)

~x

the bits of x inverted

注意事项:

  1. 负移位计数是非法的,并会导致 ValueError 要被引发。

  2. 向左移位 n 位,相当于乘以 pow(2, n) .

  3. 向右移位 n bits is equivalent to floor division by pow(2, n) .

  4. 履行这些计算,采用至少一额外符号扩展位表示有限的 2 的补码 (工作位宽 1 + max(x.bit_length(), y.bit_length()) 或更多) 足以获取与无穷多符号位相同的结果。

额外整数类型方法

int 类型实现 numbers.Integral 抽象基类 。此外,它还提供一些其它方法:

int. bit_length ( )

Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros:

>>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6