2025-10-08 Python 标准库 4——内置类型:数字类型
文章目录
- 1. 主要内置类型概述
- 2. 逻辑值检测
- 3. 布尔运算(and, or, not)
- 3.1. 布尔运算规则表
- 3.2. 重要注意点
- 4. 比较运算
- 4.1. 比较运算符规则表
- 4.2. 核心特性
- 5. 数字类型(int, float, complex)
- 5.1. 数字类型的创建与混合运算
- 5.2. 通用数字运算(复数除外)
- 5.3. 整数类型的按位运算
- 5.4. 整数类型的附加方法
- 5.4.1. `int.bit_length()`
- 5.4.2. `int.bit_count()`
- 5.4.3. `int.to_bytes(length, byteorder, *, signed=False)`
- 5.4.4. `int.from_bytes(bytes, byteorder='big', *, signed=False)`
- 5.4.5. `int.as_integer_ratio()`
- 5.4.6. `int.is_integer()`
- 5.5. 浮点类型的附加方法
- 5.5.1. `float.as_integer_ratio()`
- 5.5.2. `float.is_integer()`
- 5.5.3. `float.hex()` 与 `float.fromhex(s)`
- 5.6. 数字类型的哈希运算
- 6. 布尔类型(bool)
- 7. 总结
参考文档:内置类型 — Python 3.13.7 文档
1. 主要内置类型概述
Python的内置标准类型是语言的核心基础,直接影响代码的逻辑实现、数据处理效率与可读性。
Python的主要内置类型可分为六大类,覆盖了绝大多数日常开发场景:
- 数字(Numbers):整数(
int
)、浮点数(float
)、复数(complex
),布尔值(bool
)是整数的子类 - 序列(Sequences):字符串(
str
)、列表(list
)、元组(tuple
)、范围(range
)等 - 映射(Mappings):字典(
dict
),用于存储键值对数据 - 类(Classes):用户自定义或内置的类对象(如
int
本身就是一个类) - 实例(Instances):类实例化后的对象(如
a = 1
中a
是int
的实例) - 异常(Exceptions):用于错误处理的类型(如
TypeError
、ValueError
)
部分序列(如list
)和映射(如dict
)属于可变多项集,其修改成员的方法(如添加、删除)会原地执行,且返回值为None
(而非多项集自身)。这是Python中容易踩坑的点,需特别注意。
代码示例:可变多项集的原地操作
# 列表(可变多项集)的append方法
my_list = [1, 2, 3]
result = my_list.append(4) # 原地添加元素,无返回值(返回None)print("修改后的列表:", my_list) # 输出:修改后的列表: [1, 2, 3, 4]
print("append方法的返回值:", result) # 输出:append方法的返回值: None# 错误用法:试图用append的返回值赋值
wrong_list = my_list.append(5)
print("错误赋值的结果:", wrong_list) # 输出:错误赋值的结果: None
2. 逻辑值检测
任何Python对象都可用于逻辑判断(如if
条件、while
循环),判断依据是对象的“真值”(Truth Value)。
- 默认真值:所有对象默认视为
True
,除非其类定义了__bool__()
返回False
,或__len__()
返回0
。 - 内置假值对象(必须牢记):
- 常量:
None
、False
- 数值零:
0
(int)、0.0
(float)、0j
(complex)、Decimal(0)
、Fraction(0, 1)
- 空序列/多项集:
''
(空字符串)、()
(空元组)、[]
(空列表)、{}
(空字典)、set()
(空集合)、range(0)
(空范围)
- 常量:
代码示例:逻辑值检测
# 假值检测
print("bool(None):", bool(None)) # 输出:False
print("bool(0.0):", bool(0.0)) # 输出:False
print("bool(''):", bool('')) # 输出:False
print("bool([]):", bool([])) # 输出:False# 真值检测(非假值均为真)
print("bool(1):", bool(1)) # 输出:True
print("bool(3.14):", bool(3.14)) # 输出:True
print("bool('hello'):", bool('hello')) # 输出:True
print("bool([1,2]):", bool([1,2])) # 输出:True# 自定义对象的真值(默认True)
class MyClass:pass
obj = MyClass()
print("bool(MyClass实例):", bool(obj)) # 输出:True# 自定义假值对象(重写__bool__)
class FalseClass:def __bool__(self):return False
false_obj = FalseClass()
print("bool(FalseClass实例):", bool(false_obj)) # 输出:False
3. 布尔运算(and, or, not)
布尔运算用于组合或否定逻辑值,按优先级升序为:or
< and
< not
(not
优先级最高)。其核心特点是短路求值(避免不必要的计算)。
3.1. 布尔运算规则表
运算 | 结果说明 | 备注(短路规则) |
---|---|---|
x or y | 若x 为真则返回x ,否则返回y | 仅x 为假时才计算y |
x and y | 若x 为假则返回x ,否则返回y | 仅x 为真时才计算y |
not x | 若x 为假则返回True ,否则返回False | 无短路(仅单操作数) |
3.2. 重要注意点
or
和and
返回的是操作数本身,而非严格的True
/False
(但可视为布尔值)。not
的优先级低于比较运算符,因此not a == b
等价于not (a == b)
,而a == not b
会引发语法错误。
代码示例:布尔运算与短路求值
# 1. or运算(短路:x真则不计算y)
x = 2
y = 3
print("x or y:", x or y) # 输出:2(x为真,直接返回x)# 验证短路:y的表达式未执行
def get_y():print("get_y被调用")return 3
print("x or get_y():", x or get_y()) # 输出:2(get_y未被调用,证明短路)# 2. and运算(短路:x假则不计算y)
x = 0
print("x and y:", x and y) # 输出:0(x为假,直接返回x)# 验证短路:y的表达式未执行
print("x and get_y():", x and get_y()) # 输出:0(get_y未被调用)# 3. not运算(否定逻辑值)
print("not True:", not True) # 输出:False
print("not 0:", not 0) # 输出:True
print("not [1,2]:", not [1,2]) # 输出:False# 4. 优先级问题
a = 5
b = 3
print("not a == b:", not a == b) # 输出:True(等价于not (5==3))
# print("a == not b:", a == not b) # 报错:SyntaxError(not不能直接参与比较)
4. 比较运算
Python支持8种比较运算符,优先级高于布尔运算,且支持任意串联(如x < y <= z
),串联时仅求值一次中间变量(如y
只算一次)。
4.1. 比较运算符规则表
运算 | 含意 | 关键说明 |
---|---|---|
< | 严格小于 | 仅对有意义的类型生效(如复数不支持) |
<= | 小于或等于 | 同上 |
> | 严格大于 | 同上 |
>= | 大于或等于 | 同上 |
== | 等于 | 不同类型默认不相等(如1 == "1" 为False ) |
!= | 不等于 | 与== 逻辑相反 |
is | 对象标识(内存地址) | 检查是否为同一对象(而非值相等) |
is not | 否定对象标识 | 与is 逻辑相反 |
4.2. 核心特性
- 串联比较:
x < y <= z
等价于x < y and y <= z
,但y
仅求值一次。 - 对象标识 vs 值相等:
==
检查值是否相等,is
检查是否为同一对象(内存地址相同)。 - 类型限制:复数不支持
<
/<=
/>
/>=
,否则会引发TypeError
。
代码示例:比较运算
# 1. 基础比较
x = 2
y = 3
z = 3
print("x < y:", x < y) # 输出:True
print("y == z:", y == z) # 输出:True
print("x >= z:", x >= z) # 输出:False# 2. 串联比较(y仅求值一次)
def get_y():print("get_y被调用")return 3
print("x < get_y() <= z:", x < get_y() <= z) # 输出:get_y被调用 + True(仅调用一次)# 3. is vs ==(对象标识 vs 值相等)
a = [1, 2, 3]
b = [1, 2, 3] # 新列表,内存地址不同
c = a # 引用同一列表,内存地址相同print("a == b:", a == b) # 输出:True(值相等)
print("a is b:", a is b) # 输出:False(不同对象)
print("a is c:", a is c) # 输出:True(同一对象)# 4. 不同类型比较
print("1 == '1':", 1 == '1') # 输出:False(不同类型值不等)
print("1 == 1.0:", 1 == 1.0) # 输出:True(数字类型兼容,值相等)# 5. 复数不支持大小比较
comp1 = 1 + 2j
comp2 = 3 + 4j
# print(comp1 < comp2) # 报错:TypeError: '<' not supported between instances of 'complex' and 'complex'
5. 数字类型(int, float, complex)
数字类型是Python处理数值计算的核心,包括三类:
- 整数(int):无限精度(如
1
、-5
、1000000000000
) - 浮点数(float):双精度浮点数(如
3.14
、-0.5
、1.0e5
),精度受硬件限制(可通过sys.float_info
查看) - 复数(complex):实部+虚部(如
1+2j
、3j
),虚部用j
/J
表示,可通过z.real
(实部)、z.imag
(虚部)获取组件
此外,布尔值(bool)是int的子类,True
等价于1
,False
等价于0
(但不建议直接当作整数使用,需显式转换)。
5.1. 数字类型的创建与混合运算
- 创建方式:通过字面值(如
5
、3.14
、2+3j
)或构造函数(如int(3.8)
、float("2.5")
、complex(1, 2)
)。 - 混合运算规则:不同类型数字运算时,“较窄”类型会自动拓宽为“较宽”类型(
int
<float
<complex
),结果类型为拓宽后的类型。
代码示例:数字创建与混合运算
# 1. 数字创建
int_num = 10 # 字面值创建int
float_num = 3.14 # 字面值创建float
complex_num = 2 + 3j # 字面值创建complex# 构造函数创建
int_from_float = int(3.8) # 截断小数部分,输出:3
float_from_str = float("2.5")# 输出:2.5
complex_from_args = complex(1, 4) # 实部1,虚部4,输出:(1+4j)print("int_from_float:", int_from_float)
print("float_from_str:", float_from_str)
print("complex_from_args:", complex_from_args)# 2. 混合运算(类型拓宽)
int_float_sum = 5 + 2.0 # int拓宽为float,结果:7.0(float)
int_complex_sum = 3 + (2 + 3j) # int拓宽为complex,结果:(5+3j)(complex)
float_complex_mul = 2.5 * (1 + 2j) # float拓宽为complex,结果:(2.5+5j)print("5 + 2.0 =", int_float_sum, "类型:", type(int_float_sum)) # <class 'float'>
print("3 + (2+3j) =", int_complex_sum, "类型:", type(int_complex_sum)) # <class 'complex'>
5.2. 通用数字运算(复数除外)
除复数外,int
和float
支持以下运算(优先级参考Python运算符优先级):
运算 | 结果说明 | 备注 |
---|---|---|
x + y | x与y的和 | - |
x - y | x与y的差 | - |
x * y | x与y的积 | - |
x / y | x与y的商(浮点结果) | 如5/2=2.5 |
x // y | 整数除法(向负无穷舍入) | 如5//2=2 ,-5//2=-3 |
x % y | 取余(余数与y同号) | 公式:x = (x//y)*y + x%y |
-x | x取反 | - |
+x | x不变 | - |
abs(x) | x的绝对值 | 如abs(-3.14)=3.14 ,abs(1+2j)=√5 |
int(x) | 转换为int(截断小数) | 如int(2.9)=2 |
float(x) | 转换为float | 如float(5)=5.0 |
divmod(x,y) | 返回(x//y, x%y) | 一次计算商和余数 |
pow(x,y) | x的y次幂 | 如pow(2,3)=8 ,等价于x**y |
x**y | x的y次幂 | 如2**3=8 ,4**0.5=2.0 |
代码示例:通用数字运算
x = 7
y = 3# 基础运算
print("x + y =", x + y) # 输出:10
print("x - y =", x - y) # 输出:4
print("x * y =", x * y) # 输出:21
print("x / y =", x / y) # 输出:2.333...(float)# 整数除法与取余(向负无穷舍入)
print("x // y =", x // y) # 输出:2(7//3=2)
print("-x // y =", -x // y) # 输出:-3(-7//3=-3,向负无穷舍入)
print("x % y =", x % y) # 输出:1(7=3*2+1)
print("-x % y =", -x % y) # 输出:2(-7=3*(-3)+2,余数与y同号)# 其他运算
print("abs(-x) =", abs(-x)) # 输出:7(绝对值)
print("divmod(x, y) =", divmod(x, y)) # 输出:(2, 1)(商+余数)
print("pow(x, 2) =", pow(x, 2)) # 输出:49(7的2次幂)
print("x ** 0.5 =", x ** 0.5) # 输出:2.645...(7的平方根)
5.3. 整数类型的按位运算
按位运算仅对int
生效,基于二进制补码规则计算,优先级:|
(或) < ^
(异或) < &
(与) < <<
/>>
(移位) < ~
(取反)。
运算 | 结果说明 | 备注 |
---|---|---|
`x | y` | 按位或(有1则1) |
x ^ y | 按位异或(不同则1) | 如3(11)^5(101)=6(110) |
x & y | 按位与(全1则1) | 如3(11)&5(101)=1(001) |
x << n | 左移n位(补0) | 等价于x * 2^n ,如3<<2=12(1100) |
x >> n | 右移n位(补符号位) | 等价于x // 2^n ,如12>>2=3(11) |
~x | 按位取反(~x = -x-1) | 如~3 = -4 ,~-4 = 3 |
代码示例:整数按位运算
a = 6 # 二进制:0110
b = 3 # 二进制:0011# 按位或、异或、与
print("a | b =", a | b) # 0110 | 0011 = 0111 → 7
print("a ^ b =", a ^ b) # 0110 ^ 0011 = 0101 → 5
print("a & b =", a & b) # 0110 & 0011 = 0010 → 2# 移位运算
print("a << 2 =", a << 2) # 0110 << 2 → 11000 → 24(6*2^2=24)
print("a >> 1 =", a >> 1) # 0110 >> 1 → 0011 → 3(6//2^1=3)
# print("a << -1") # 报错:ValueError(负移位数非法)# 按位取反(~x = -x-1)
print("~a =", ~a) # ~6 = -7(验证:-6-1=-7)
print("~b =", ~b) # ~3 = -4(验证:-3-1=-4)
5.4. 整数类型的附加方法
int
类型提供多个实用方法,用于二进制操作、字节转换等:
5.4.1. int.bit_length()
返回表示整数所需的二进制位数,常用于判断整数的范围。Python 3.1+ 新增。
n1 = 10 # 二进制:1010 → 4位
n2 = -37 # 二进制:-100101 → 绝对值100101是6位
print("n1.bit_length():", n1.bit_length()) # 输出:4
print("n2.bit_length():", n2.bit_length()) # 输出:6(忽略负号)
print("0.bit_length():", 0.bit_length()) # 输出:0(特殊情况)
5.4.2. int.bit_count()
返回整数绝对值的二进制表示中“1”的数量。Python 3.10+ 新增。
n = 19 # 二进制:10011 → 3个1
print("n.bit_count():", n.bit_count()) # 输出:3
print("(-n).bit_count():", (-n).bit_count()) # 输出:3(忽略负号)
print("0.bit_count():", 0.bit_count()) # 输出:0
5.4.3. int.to_bytes(length, byteorder, *, signed=False)
将整数转换为指定长度和字节序的字节数组,signed
指定是否用补码表示负数。Python 3.2+ 新增,Python 3.11 版本变更:添加了length
和byteorder
的默认参数值。
# 示例1:1024转换为2字节大端序
num1 = 1024
bytes1 = num1.to_bytes(2, byteorder='big')
print("1024.to_bytes(2, 'big'):", bytes1) # 输出:b'\x04\x00'# 示例2:-1024转换为10字节大端序(需signed=True)
num2 = -1024
bytes2 = num2.to_bytes(10, byteorder='big', signed=True)
print("-1024.to_bytes(10, 'big', True):", bytes2) # 输出:b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'# 示例3:自动计算所需长度((bit_length +7)//8)
num3 = 1000
length = (num3.bit_length() + 7) // 8 # 1000.bit_length()=10 → (10+7)//8=2
bytes3 = num3.to_bytes(length, byteorder='little')
print("1000.to_bytes(2, 'little'):", bytes3) # 输出:b'\xe8\x03'# 错误:长度不足(500需2字节,1字节会溢出)
# num4 = 500
# num4.to_bytes(1, 'big') # 报错:OverflowError
5.4.4. int.from_bytes(bytes, byteorder='big', *, signed=False)
将字节数组还原为整数,与to_bytes
互为逆操作。Python 3.2+ 新增,Python 3.11 版本变更:添加了byteorder
的默认参数值。
# 示例1:从大端序字节数组还原16
bytes1 = b'\x00\x10'
num1 = int.from_bytes(bytes1, byteorder='big')
print("int.from_bytes(b'\\x00\\x10', 'big'):", num1) # 输出:16# 示例2:从小端序字节数组还原4096
bytes2 = b'\x10\x00'
num2 = int.from_bytes(bytes2, byteorder='little')
print("int.from_bytes(b'\\x10\\x00', 'little'):", num2) # 输出:4096# 示例3:从补码字节数组还原负数
bytes3 = b'\xfc\x00'
num3 = int.from_bytes(bytes3, byteorder='big', signed=True)
print("int.from_bytes(b'\\xfc\\x00', 'big', True):", num3) # 输出:-1024
5.4.5. int.as_integer_ratio()
返回(整数, 1)
,因整数可表示为“自身/1”。Python 3.8+ 新增。
n = 5
ratio = n.as_integer_ratio()
print("5.as_integer_ratio():", ratio) # 输出:(5, 1)n_neg = -8
ratio_neg = n_neg.as_integer_ratio()
print("-8.as_integer_ratio():", ratio_neg) # 输出:(-8, 1)(分母始终为正)
5.4.6. int.is_integer()
始终返回True
,用于与float.is_integer()
保持接口一致。Python 3.12+ 新增。
n = 10
print("10.is_integer():", n.is_integer()) # 输出:Truen_neg = -3
print("-3.is_integer():", n_neg.is_integer()) # 输出:True
5.5. 浮点类型的附加方法
float
类型提供针对浮点数的特殊方法,如分数转换、十六进制表示等:
5.5.1. float.as_integer_ratio()
将浮点数表示为(分子, 分母)
(分母为正,且分子与分母互质)。
f1 = 2.0 # 2.0 = 2/1
print("2.0.as_integer_ratio():", f1.as_integer_ratio()) # 输出:(2, 1)f2 = 3.5 # 3.5 = 7/2
print("3.5.as_integer_ratio():", f2.as_integer_ratio()) # 输出:(7, 2)f3 = 0.1 # 注意:0.1无法精确表示为二进制浮点数,实际是6004799503160661/60047995031606616
print("0.1.as_integer_ratio():", f3.as_integer_ratio()) # 输出:(3602879701896397, 36028797018963968)# 特殊值:inf和nan会报错
# f_inf = float('inf')
# f_inf.as_integer_ratio() # 报错:OverflowError
# f_nan = float('nan')
# f_nan.as_integer_ratio() # 报错:ValueError
5.5.2. float.is_integer()
若浮点数无小数部分(如2.0
),返回True
;否则返回False
。
print("2.0.is_integer():", 2.0.is_integer()) # 输出:True
print("3.14.is_integer():", 3.14.is_integer()) # 输出:False
print("-5.0.is_integer():", (-5.0).is_integer()) # 输出:True
print("0.0.is_integer():", 0.0.is_integer()) # 输出:True
5.5.3. float.hex()
与 float.fromhex(s)
由于浮点数在内存中以二进制存储,十进制字符串转换可能有误差,而十六进制可精确表示浮点数,适合调试。
float.hex()
:将浮点数转换为十六进制字符串(格式:0x整数.小数p指数
)。float.fromhex(s)
:从十六进制字符串还原浮点数(类方法)。
# 示例1:3.0的十六进制表示
f = 3.0
hex_str = f.hex()
print("3.0.hex():", hex_str) # 输出:0x1.8p+1(解析:1.8(十六进制)=1+8/16=1.5 → 1.5*2^1=3.0)# 示例2:从十六进制字符串还原浮点数
f_restored = float.fromhex(hex_str)
print("float.fromhex('0x1.8p+1'):", f_restored) # 输出:3.0# 示例3:复杂浮点数的转换
f2 = 3740.0
hex_str2 = f2.hex()
print("3740.0.hex():", hex_str2) # 输出:0x1.d380000000000p+11
f2_restored = float.fromhex(hex_str2)
print("还原后:", f2_restored) # 输出:3740.0
5.6. 数字类型的哈希运算
哈希运算(hash()
)的核心规则是:若x == y
,则hash(x) == hash(y)
,确保相同值的对象在哈希表(如dict
)中被正确识别。
Python对数字的哈希基于“质数取模”(质数P
可通过sys.hash_info.modulus
查看),核心逻辑:
- 有理数
x = m/n
:若n
不被P
整除,hash(x) = (m * n的逆模P) % P
;若n
被P
整除,hash(x) = sys.hash_info.inf
。 - 负数:
hash(-x) = -hash(x)
(若结果为-1
,替换为-2
)。 - 复数:
hash(z) = (hash(z.real) + sys.hash_info.imag * hash(z.imag)) % 2^width
。
代码示例:数字哈希
import sys# 1. 相同值的不同数字类型,哈希相同
print("hash(1) =", hash(1)) # 输出:1
print("hash(1.0) =", hash(1.0)) # 输出:1(1 == 1.0 → 哈希相同)
print("hash(True) =", hash(True)) # 输出:1(True == 1 → 哈希相同)# 2. 浮点数与分数的哈希相同
from fractions import Fraction
f = Fraction(3, 2) # 1.5
print("hash(1.5) =", hash(1.5))
print("hash(Fraction(3,2)) =", hash(f)) # 输出与hash(1.5)相同# 3. 复数的哈希
comp = 1 + 2j
print("hash(1+2j) =", hash(comp))# 4. 查看哈希相关参数
print("哈希质数P =", sys.hash_info.modulus) # 输出:9223372036854775807(64位系统)
print("哈希宽度 =", sys.hash_info.width) # 输出:64(64位系统)
6. 布尔类型(bool)
bool
是int
的子类,仅包含两个实例:True
(等价于1
)和False
(等价于0
),用于表示逻辑真假。
- 转换方法:
bool(x)
根据x
的真值返回True
/False
(参见2.1节逻辑值检测)。 - 运算支持:
- 逻辑运算:推荐使用
and
/or
/not
(符合逻辑语义)。 - 按位运算:
&
/|
/^
可用于布尔值,但Python 3.12 版本弃用:使用按位取反运算符~
已被弃用,Python 3.16+ 将引发错误。
- 逻辑运算:推荐使用
- 整数兼容性:
True + 1 = 2
、False * 3 = 0
,但不建议直接当作整数使用,需显式用int()
转换。
代码示例:布尔类型
# 1. 布尔值与整数的关系
print("True == 1:", True == 1) # 输出:True
print("False == 0:", False == 0) # 输出:True
print("True + 2:", True + 2) # 输出:3(True=1)
print("False * 5:", False * 5) # 输出:0(False=0)# 2. 逻辑运算 vs 按位运算
a = True
b = False
print("a and b:", a and b) # 输出:False(逻辑与)
print("a & b:", a & b) # 输出:False(按位与,结果相同但语义不同)
print("a or b:", a or b) # 输出:True(逻辑或)
print("a | b:", a | b) # 输出:True(按位或)# 3. 弃用的按位取反(Python 3.12+警告)
# print(~a) # 输出:-2,但会触发DeprecationWarning,3.16+报错
print("not a:", not a) # 推荐用not,输出:False# 4. bool()转换
print("bool('python'):", bool('python')) # 输出:True
print("bool(0):", bool(0)) # 输出:False
7. 总结
- 逻辑值检测:牢记假值对象,避免因“空对象”导致的逻辑错误。
- 布尔运算:短路求值是优化性能的关键,
and
/or
返回操作数而非严格布尔值。 - 比较运算:
is
检查对象标识,==
检查值相等;支持串联比较但需注意类型兼容性。 - 数字类型:
int
无限精度、float
双精度、complex
处理虚数,附加方法(如bit_length
、as_integer_ratio
)提升数值处理灵活性。