一、什么是内置函数?
内置函数(Built-in Functions)是 Python 解释器自带的函数,不需要 import 任何模块,打开 Python 就能直接用。
# 不需要任何 import,直接用!print("Hello") # ✅ 直接用len([1, 2, 3]) # ✅ 直接用max(1, 2, 3) # ✅ 直接用# 对比:非内置函数需要导入import mathmath.sqrt(16) # 需要 import math
Python 3.12 共有 69 个内置函数。下面按功能分类逐一讲解。
二、数据类型转换类
2.1 int() —— 转为整数
# ============ 基本用法 ============print(int(3.14)) # 3(截断小数,不是四舍五入!)print(int(3.99)) # 3(还是截断)print(int(-3.99)) # -3(向零方向截断)print(int("42")) # 42(字符串 → 整数)print(int(" 10 ")) # 10(自动去掉首尾空格)print(int(True)) # 1(True → 1)print(int(False)) # 0(False → 0)# ============ 指定进制 ============# int(字符串, 进制)print(int("1010", 2)) # 10(二进制 1010 = 十进制 10)print(int("FF", 16)) # 255(十六进制 FF = 十进制 255)print(int("77", 8)) # 63(八进制 77 = 十进制 63)print(int("0xFF", 16)) # 255(带前缀也行)print(int("0b1010", 2)) # 10(带前缀也行)# ============ 常见错误 ============# int("3.14") # ❌ ValueError! 不能直接转小数字符串# int("hello") # ❌ ValueError! 不是数字# int("") # ❌ ValueError! 空字符串# ✅ 正确做法:先转 float 再转 intprint(int(float("3.14"))) # 3
📌 注意:int() 是截断小数,不是四舍五入!要四舍五入用 round()。
2.2 float() —— 转为浮点数
print(float(42)) # 42.0print(float("3.14")) # 3.14print(float("1e3")) # 1000.0(科学计数法)print(float("inf")) # inf(无穷大)print(float("-inf")) # -inf(负无穷大)print(float("nan")) # nan(非数字)print(float(True)) # 1.0print(float(False)) # 0.0# 常见错误# float("hello") # ❌ ValueError
2.3 str() —— 转为字符串
print(str(42)) # "42"print(str(3.14)) # "3.14"print(str(True)) # "True"print(str(None)) # "None"print(str([1, 2, 3])) # "[1, 2, 3]"print(str({"a": 1})) # "{'a': 1}"# 任何对象都可以转为字符串class Dog: def __str__(self): return "🐕 一只可爱的狗"d = Dog()print(str(d)) # 🐕 一只可爱的狗
2.4 bool() —— 转为布尔值
# ============ 以下值转为 False("假值") ============print(bool(0)) # Falseprint(bool(0.0)) # Falseprint(bool("")) # False(空字符串)print(bool([])) # False(空列表)print(bool({})) # False(空字典)print(bool(())) # False(空元组)print(bool(set())) # False(空集合)print(bool(None)) # False# ============ 其他所有值都是 True ============print(bool(1)) # Trueprint(bool(-1)) # True(负数也是True!)print(bool("hello")) # Trueprint(bool(" ")) # True(空格字符串也是True!)print(bool([0])) # True(列表里有元素就是True)print(bool([False])) # True(列表非空就是True)# ============ 实际应用 ============name = input("请输入名字:")if bool(name): # 等价于 if name: print(f"你好,{name}")else: print("你没有输入名字")
📌 记忆口诀:零、空、None 为 False,其余全为 True。
2.5 list()、tuple()、set()、dict() —— 容器转换
# ============ list():转为列表 ============print(list("hello")) # ['h', 'e', 'l', 'l', 'o']print(list((1, 2, 3))) # [1, 2, 3](元组→列表)print(list({1, 2, 3})) # [1, 2, 3](集合→列表)print(list(range(5))) # [0, 1, 2, 3, 4]print(list({"a": 1, "b": 2})) # ['a', 'b'](字典→键的列表)# ============ tuple():转为元组 ============print(tuple([1, 2, 3])) # (1, 2, 3)print(tuple("abc")) # ('a', 'b', 'c')# ============ set():转为集合(自动去重) ============print(set([1, 2, 2, 3, 3, 3])) # {1, 2, 3}print(set("hello")) # {'h', 'e', 'l', 'o'}(去重了)# ============ dict():创建字典 ============print(dict(a=1, b=2, c=3)) # {'a': 1, 'b': 2, 'c': 3}print(dict([("a", 1), ("b", 2)])) # {'a': 1, 'b': 2}print(dict(zip(["a", "b"], [1, 2]))) # {'a': 1, 'b': 2}
2.6 bytes() 和 bytearray()
# bytes():创建不可变字节序列b = bytes("你好", encoding="utf-8")print(b) # b'\xe4\xbd\xa0\xe5\xa5\xbd'print(len(b)) # 6(UTF-8中一个中文占3字节)# bytearray():创建可变字节序列ba = bytearray(b"hello")ba[0] = 72 # 可以修改!print(ba) # bytearray(b'Hello')
2.7 complex() —— 复数
c = complex(3, 4) # 3 + 4jprint(c) # (3+4j)print(c.real) # 3.0(实部)print(c.imag) # 4.0(虚部)c2 = complex("1+2j") # 从字符串创建print(c2) # (1+2j)
2.8 chr() 和 ord() —— 字符与编码互转
# chr():数字 → 字符(Unicode码点 → 字符)print(chr(65)) # Aprint(chr(97)) # aprint(chr(20013)) # 中print(chr(128512)) # 😀# ord():字符 → 数字(字符 → Unicode码点)print(ord("A")) # 65print(ord("a")) # 97print(ord("中")) # 20013print(ord("😀")) # 128512# 实际应用:生成字母表alphabet = [chr(i) for i in range(65, 91)]print(alphabet)# ['A', 'B', 'C', ..., 'Z']# 实际应用:简单加密(凯撒密码)def caesar_encrypt(text, shift=3): result = "" for ch in text: if ch.isalpha(): base = ord('A') if ch.isupper() else ord('a') result += chr((ord(ch) - base + shift) % 26 + base) else: result += ch return resultprint(caesar_encrypt("Hello World")) # Khoor Zruog
三、数学计算类
3.1 abs() —— 绝对值
print(abs(-5)) # 5print(abs(5)) # 5print(abs(-3.14)) # 3.14print(abs(3 - 4j)) # 5.0(复数的模:√(3²+4²))# 实际应用:计算两点之间的距离(一维)pos_a = 10pos_b = -3distance = abs(pos_a - pos_b)print(f"距离:{distance}") # 13
3.2 round() —— 四舍五入
# round(数字, 小数位数)print(round(3.14159, 2)) # 3.14print(round(3.14159, 3)) # 3.142print(round(3.14159)) # 3(不传第二个参数,取整)print(round(3.5)) # 4print(round(2.5)) # 2 ⚠️ 不是3!# ⚠️ 银行家舍入(四舍六入五成双)# 当恰好是 .5 时,舍入到最近的偶数print(round(0.5)) # 0(舍入到偶数0)print(round(1.5)) # 2(舍入到偶数2)print(round(2.5)) # 2(舍入到偶数2)print(round(3.5)) # 4(舍入到偶数4)print(round(4.5)) # 4(舍入到偶数4)# 负数print(round(-2.5)) # -2print(round(-3.5)) # -4# 实际应用:保留两位小数price = 19.999print(f"价格:¥{round(price, 2)}") # 价格:¥20.0
📌 如果需要精确的十进制运算(如金融),用 decimal.Decimal。
3.3 max() 和 min() —— 最大值/最小值
# ============ 多个参数 ============print(max(1, 2, 3, 4, 5)) # 5print(min(1, 2, 3, 4, 5)) # 1print(max("apple", "banana", "cherry")) # "cherry"(按字典序)# ============ 可迭代对象 ============numbers = [3, 1, 4, 1, 5, 9, 2, 6]print(max(numbers)) # 9print(min(numbers)) # 1# ============ key 参数(自定义比较规则) ============words = ["apple", "pie", "banana", "a"]# 按长度找最长/最短print(max(words, key=len)) # "banana"(最长)print(min(words, key=len)) # "a"(最短)# 按绝对值找最大nums = [-10, 3, -7, 5]print(max(nums, key=abs)) # -10(绝对值最大)# 字典列表:按某个字段找最大students = [ {"name": "张三", "score": 92}, {"name": "李四", "score": 85}, {"name": "王五", "score": 98},]best = max(students, key=lambda s: s["score"])print(f"最高分:{best['name']}({best['score']}分)")# 输出:最高分:王五(98分)# ============ default 参数(可迭代对象为空时) ============empty_list = []# max(empty_list) # ❌ ValueError!print(max(empty_list, default=0)) # 0(安全写法)
3.4 sum() —— 求和
# sum(可迭代对象, 起始值)print(sum([1, 2, 3, 4, 5])) # 15print(sum([1, 2, 3], 10)) # 16(10 + 1 + 2 + 3)print(sum(range(101))) # 5050(0+1+2+...+100)# 浮点数print(sum([0.1, 0.2, 0.3])) # 0.6000000000000001(浮点精度问题)# 实际应用:计算总分scores = [92, 85, 78, 96, 88]total = sum(scores)average = total / len(scores)print(f"总分:{total},平均分:{average:.1f}")# 输出:总分:439,平均分:87.8# ⚠️ sum() 只能用于数字!# sum(["a", "b", "c"]) # ❌ TypeError# 字符串拼接用 "".join()print("".join(["a", "b", "c"])) # "abc"
3.5 pow() —— 幂运算
# pow(底数, 指数)print(pow(2, 10)) # 1024(2的10次方)print(pow(3, 3)) # 27# 等价于 ** 运算符print(2 ** 10) # 1024# pow(底数, 指数, 模数):取模幂运算(密码学常用)print(pow(2, 10, 1000)) # 24(2^10 = 1024,1024 % 1000 = 24)# 比 (2**10) % 1000 更高效(大数时)
3.6 divmod() —— 商和余数
# divmod(被除数, 除数) → 返回 (商, 余数)print(divmod(17, 5)) # (3, 2) 因为 17 = 3×5 + 2print(divmod(100, 7)) # (14, 2) 因为 100 = 14×7 + 2print(divmod(10, 3)) # (3, 1)# 等价于:# (17 // 5, 17 % 5)# 实际应用:秒数转为 时:分:秒total_seconds = 3661hours, remainder = divmod(total_seconds, 3600)minutes, seconds = divmod(remainder, 60)print(f"{hours:02d}:{minutes:02d}:{seconds:02d}")# 输出:01:01:01
四、序列/迭代操作类
4.1 len() —— 长度
print(len("hello")) # 5print(len([1, 2, 3])) # 3print(len((1, 2, 3, 4))) # 4print(len({"a": 1, "b": 2})) # 2(字典的键值对数量)print(len({1, 2, 3})) # 3(集合元素数量)print(len(range(10))) # 10print(len(b"hello")) # 5(字节串)# 实际应用:判断是否为空my_list = []if len(my_list) == 0: print("列表为空")# 更 Pythonic 的写法:if not my_list: print("列表为空")
4.2 range() —— 生成整数序列
# range(stop):从0到stop-1print(list(range(5))) # [0, 1, 2, 3, 4]# range(start, stop):从start到stop-1print(list(range(2, 7))) # [2, 3, 4, 5, 6]# range(start, stop, step):带步长print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8](偶数)print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1](倒序)print(list(range(1, 20, 3))) # [1, 4, 7, 10, 13, 16, 19]# 常用于 for 循环for i in range(5): print(i, end=" ") # 0 1 2 3 4print()# 生成索引fruits = ["苹果", "香蕉", "橘子"]for i in range(len(fruits)): print(f" {i}: {fruits[i]}")
4.3 enumerate() —— 带索引遍历
# enumerate(可迭代对象, start=起始索引)fruits = ["苹果", "香蕉", "橘子", "葡萄"]# ❌ 不推荐的写法for i in range(len(fruits)): print(f"{i}: {fruits[i]}")# ✅ 推荐:用 enumeratefor index, fruit in enumerate(fruits): print(f" {index}: {fruit}")# 输出:# 0: 苹果# 1: 香蕉# 2: 橘子# 3: 葡萄# 从1开始编号for num, fruit in enumerate(fruits, start=1): print(f" 第{num}个:{fruit}")# 输出:# 第1个:苹果# 第2个:香蕉# ...
4.4 zip() —— 打包多个序列
# zip() 将多个可迭代对象"拉链式"配对names = ["张三", "李四", "王五"]scores = [92, 85, 78]ages = [20, 21, 22]# 基本用法for name, score in zip(names, scores): print(f" {name}: {score}分")# 输出:# 张三: 92分# 李四: 85分# 王五: 78分# 三个序列for name, score, age in zip(names, scores, ages): print(f" {name}({age}岁): {score}分")# 转为列表paired = list(zip(names, scores))print(paired) # [('张三', 92), ('李四', 85), ('王五', 78)]# 转为字典score_dict = dict(zip(names, scores))print(score_dict) # {'张三': 92, '李四': 85, '王五': 78}# ⚠️ 长度不同时,以最短的为准a = [1, 2, 3, 4, 5]b = ["a", "b", "c"]print(list(zip(a, b))) # [(1, 'a'), (2, 'b'), (3, 'c')](4和5被丢弃)# 如果想保留所有元素(Python 3.10+)from itertools import zip_longestprint(list(zip_longest(a, b, fillvalue=None)))# [(1, 'a'), (2, 'b'), (3, 'c'), (4, None), (5, None)]# 解压(zip 的逆操作)pairs = [('张三', 92), ('李四', 85), ('王五', 78)]names2, scores2 = zip(*pairs) # 注意 * 号!print(names2) # ('张三', '李四', '王五')print(scores2) # (92, 85, 78)
4.5 map() —— 批量转换
# map(函数, 可迭代对象) → 对每个元素应用函数# 示例1:所有数字平方numbers = [1, 2, 3, 4, 5]squared = map(lambda x: x ** 2, numbers)print(list(squared)) # [1, 4, 9, 16, 25]# 示例2:字符串转整数str_nums = ["1", "2", "3", "4", "5"]int_nums = map(int, str_nums)print(list(int_nums)) # [1, 2, 3, 4, 5]# 示例3:多个序列a = [1, 2, 3]b = [10, 20, 30]sums = map(lambda x, y: x + y, a, b)print(list(sums)) # [11, 22, 33]# 示例4:字符串处理words = ["hello", "world", "python"]upper_words = map(str.upper, words)print(list(upper_words)) # ['HELLO', 'WORLD', 'PYTHON']# ⚠️ map 返回的是迭代器,只能遍历一次!m = map(lambda x: x*2, [1, 2, 3])print(list(m)) # [2, 4, 6]print(list(m)) # [](已经耗尽了!)
4.6 filter() —— 过滤
# filter(函数, 可迭代对象) → 保留函数返回 True 的元素# 示例1:过滤偶数numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]evens = filter(lambda x: x % 2 == 0, numbers)print(list(evens)) # [2, 4, 6, 8, 10]# 示例2:过滤非空字符串data = ["hello", "", "world", None, "python", ""]clean = filter(None, data) # None 表示过滤掉"假值"print(list(clean)) # ['hello', 'world', 'python']# 示例3:过滤及格的学生students = [ {"name": "张三", "score": 92}, {"name": "李四", "score": 45}, {"name": "王五", "score": 78}, {"name": "赵六", "score": 55},]passed = filter(lambda s: s["score"] >= 60, students)for s in passed: print(f" ✅ {s['name']}: {s['score']}分")# 输出:# ✅ 张三: 92分# ✅ 王五: 78分
4.7 sorted() —— 排序
# sorted(可迭代对象, key=排序依据, reverse=是否降序)# 返回新列表(不修改原列表)# ============ 基本排序 ============numbers = [3, 1, 4, 1, 5, 9, 2, 6]print(sorted(numbers)) # [1, 1, 2, 3, 4, 5, 6, 9](升序)print(sorted(numbers, reverse=True)) # [9, 6, 5, 4, 3, 2, 1, 1](降序)# 字符串排序(按字典序)words = ["banana", "apple", "cherry", "date"]print(sorted(words)) # ['apple', 'banana', 'cherry', 'date']# ============ key 参数 ============# 按长度排序words = ["hi", "hello", "a", "world"]print(sorted(words, key=len)) # ['a', 'hi', 'hello', 'world']# 按绝对值排序nums = [-5, 3, -1, 4, -2]print(sorted(nums, key=abs)) # [-1, -2, 3, 4, -5]# 字典列表排序students = [ {"name": "张三", "score": 92, "age": 20}, {"name": "李四", "score": 85, "age": 22}, {"name": "王五", "score": 98, "age": 21},]# 按分数降序by_score = sorted(students, key=lambda s: s["score"], reverse=True)for s in by_score: print(f" {s['name']}: {s['score']}分")# 多条件排序:先按分数降序,分数相同按年龄升序data = [("张三", 90, 20), ("李四", 90, 22), ("王五", 95, 21)]result = sorted(data, key=lambda x: (-x[1], x[2]))print(result) # [('王五', 95, 21), ('张三', 90, 20), ('李四', 90, 22)]# ============ sorted vs list.sort() ============original = [3, 1, 2]new_list = sorted(original) # 返回新列表,原列表不变print(original) # [3, 1, 2](没变)print(new_list) # [1, 2, 3]original.sort() # 原地排序,修改原列表print(original) # [1, 2, 3](变了)
4.8 reversed() —— 反转
# reversed() 返回反转的迭代器# 列表print(list(reversed([1, 2, 3, 4, 5]))) # [5, 4, 3, 2, 1]# 字符串print("".join(reversed("hello"))) # "olleh"# rangeprint(list(reversed(range(5)))) # [4, 3, 2, 1, 0]# ⚠️ reversed 不修改原对象original = [1, 2, 3]rev = reversed(original)print(original) # [1, 2, 3](没变)print(list(rev)) # [3, 2, 1]
4.9 all() 和 any() —— 全部/任一判断
# all():所有元素都为真 → True(全真才真)# any():任一元素为真 → True(一真即真)# ============ all() ============print(all([True, True, True])) # Trueprint(all([True, False, True])) # False(有一个False)print(all([1, 2, 3])) # True(都是真值)print(all([1, 0, 3])) # False(0是假值)print(all([])) # True(空列表,vacuous truth)# 实际应用:检查所有成绩是否及格scores = [92, 85, 78, 96, 88]print(f"全部及格?{all(s >= 60for s in scores)}") # Truescores2 = [92, 45, 78, 96, 88]print(f"全部及格?{all(s >= 60for s in scores2)}") # False# ============ any() ============print(any([False, False, True])) # True(有一个True)print(any([False, False, False])) # Falseprint(any([0, 0, 1])) # Trueprint(any([])) # False(空列表)# 实际应用:检查是否有不及格的print(f"有不及格?{any(s < 60for s in scores2)}") # True# 实际应用:检查密码是否包含特殊字符password = "abc123!"special_chars = "!@#$%^&*"has_special = any(c in special_chars for c in password)print(f"包含特殊字符?{has_special}") # True
4.10 iter() 和 next() —— 迭代器
# iter():创建迭代器# next():获取下一个元素# 基本用法my_list = [10, 20, 30]it = iter(my_list) # 创建迭代器print(next(it)) # 10print(next(it)) # 20print(next(it)) # 30# print(next(it)) # ❌ StopIteration 异常!# 安全写法:提供默认值it = iter(my_list)print(next(it, "没了")) # 10print(next(it, "没了")) # 20print(next(it, "没了")) # 30print(next(it, "没了")) # "没了"(不报错)# 实际应用:手动实现 for 循环fruits = ["苹果", "香蕉", "橘子"]it = iter(fruits)while True: try: fruit = next(it) print(f" 吃到:{fruit}") except StopIteration: break# 这就是 for 循环的底层原理!
4.11 slice() —— 切片对象
# slice(start, stop, step) 创建切片对象# 通常我们这样切片:my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]print(my_list[2:7:2]) # [2, 4, 6]# 等价于:s = slice(2, 7, 2)print(my_list[s]) # [2, 4, 6]# 实际应用:复用切片data = list(range(20))even_slice = slice(0, None, 2) # 所有偶数索引odd_slice = slice(1, None, 2) # 所有奇数索引print(data[even_slice]) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]print(data[odd_slice]) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
五、字符串/表示相关
5.1 repr() —— 官方表示形式
# repr() 返回对象的"官方"字符串表示(用于调试)# str() 返回"友好"的字符串表示(用于展示)s = "hello\nworld"print(str(s)) # hello # world(换行了)print(repr(s)) # 'hello\nworld'(显示转义字符)# 对比print(str(42)) # 42print(repr(42)) # 42print(str("hi")) # hiprint(repr("hi")) # 'hi'(带引号)# 自定义类class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"({self.x}, {self.y})" # 给用户看的 def __repr__(self): return f"Point({self.x}, {self.y})" # 给开发者看的p = Point(3, 4)print(str(p)) # (3, 4)print(repr(p)) # Point(3, 4)print(p) # (3, 4)(print 默认调用 __str__)# 在列表中,显示的是 reprprint([p]) # [Point(3, 4)](列表中用 __repr__)
5.2 ascii() —— ASCII 表示
# 类似 repr(),但非 ASCII 字符会被转义print(ascii("你好")) # '\u4f60\u597d'print(ascii("hello")) # 'hello'(纯ASCII不变)print(repr("你好")) # '你好'(repr 保留中文)
5.3 format() —— 格式化
# format(值, 格式说明)print(format(3.14159, ".2f")) # "3.14"print(format(42, "08d")) # "00000042"(补零到8位)print(format(255, "x")) # "ff"(十六进制)print(format(255, "b")) # "11111111"(二进制)print(format(0.85, "%")) # "85.000000%"print(format(1234567, ",")) # "1,234,567"(千分位)# 通常用 f-string 更方便:x = 3.14159print(f"{x:.2f}") # 3.14
六、对象/反射相关
6.1 type() —— 获取类型
print(type(42)) # <class 'int'>print(type(3.14)) # <class 'float'>print(type("hello")) # <class 'str'>print(type([1, 2])) # <class 'list'>print(type({"a": 1})) # <class 'dict'>print(type(None)) # <class 'NoneType'># 判断类型(推荐用 isinstance)x = 42if type(x) == int: # 能用,但不推荐 print("是整数")if isinstance(x, int): # ✅ 推荐(支持继承) print("是整数")
6.2 isinstance() —— 类型判断
# isinstance(对象, 类型) → True/False# 支持继承关系!print(isinstance(42, int)) # Trueprint(isinstance("hi", str)) # Trueprint(isinstance([1,2], list)) # Trueprint(isinstance(True, int)) # True!(bool 是 int 的子类)# 可以传元组(满足其一即可)x = 3.14print(isinstance(x, (int, float))) # True(是 int 或 float 之一)# 支持继承class Animal: passclass Dog(Animal): passd = Dog()print(isinstance(d, Dog)) # Trueprint(isinstance(d, Animal)) # True(Dog 继承自 Animal)print(type(d) == Animal) # False(type 不考虑继承)# 实际应用:函数参数检查def process(data): if isinstance(data, str): return data.upper() elif isinstance(data, (int, float)): return data * 2 elif isinstance(data, list): return len(data) else: raise TypeError(f"不支持的类型:{type(data)}")print(process("hello")) # HELLOprint(process(21)) # 42print(process([1,2,3])) # 3
6.3 issubclass() —— 类继承判断
class Animal: passclass Dog(Animal): passclass Cat(Animal): passprint(issubclass(Dog, Animal)) # Trueprint(issubclass(Cat, Animal)) # Trueprint(issubclass(Dog, Cat)) # Falseprint(issubclass(bool, int)) # True(bool 继承自 int)
6.4 id() —— 对象内存地址
# id() 返回对象的唯一标识(内存地址)a = [1, 2, 3]b = [1, 2, 3]c = aprint(id(a)) # 140234567890(某个内存地址)print(id(b)) # 140234567891(不同!虽然内容相同)print(id(c)) # 140234567890(和a相同!因为是同一个对象)print(a == b) # True(值相等)print(a is b) # False(不是同一个对象)print(a is c) # True(是同一个对象)# 小整数缓存(-5 到 256)x = 100y = 100print(x is y) # True(小整数被缓存,共享同一对象)x = 1000y = 1000print(x is y) # False(大整数不缓存)
6.5 hash() —— 哈希值
# hash() 返回对象的哈希值(整数)print(hash("hello")) # 某个整数print(hash(42)) # 42(整数的哈希通常是自身)print(hash((1, 2, 3))) # 元组可以哈希# ❌ 可变对象不能哈希# hash([1, 2, 3]) # TypeError: unhashable type: 'list'# hash({"a": 1}) # TypeError: unhashable type: 'dict'# 应用:字典的键和集合的元素必须是可哈希的# 这就是为什么列表不能做字典的键,但元组可以d = {(1, 2): "point"} # ✅ 元组可以做键# d = {[1, 2]: "point"} # ❌ 列表不行
6.6 callable() —— 是否可调用
# callable() 判断对象是否可以被调用(加括号执行)print(callable(print)) # True(函数可调用)print(callable(len)) # Trueprint(callable(lambda x: x)) # Trueprint(callable(42)) # False(数字不可调用)print(callable("hello")) # Falseprint(callable([1, 2])) # Falseclass MyClass: def __call__(self): return "我被调用了"obj = MyClass()print(callable(obj)) # True(定义了 __call__)print(obj()) # "我被调用了"
6.7 dir() —— 列出属性和方法
# dir() 列出对象的所有属性和方法print(dir("hello"))# ['__add__', '__class__', ..., 'upper', 'lower', 'split', 'strip', ...]# 过滤出非下划线开头的(实用方法)methods = [m for m in dir("hello") if not m.startswith("_")]print(methods)# ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', # 'find', 'format', 'index', 'isalnum', 'isalpha', ..., 'upper', 'zfill']# 查看模块有什么import mathprint([x for x in dir(math) if not x.startswith("_")])# ['acos', 'asin', 'atan', 'ceil', 'cos', 'e', 'exp', 'floor', 'log', 'pi', 'sin', 'sqrt', ...]
6.8 getattr()、setattr()、hasattr()、delattr()
class Student: def __init__(self, name, age): self.name = name self.age = age def greet(self): return f"你好,我是{self.name}"s = Student("张三", 20)# ============ getattr:获取属性 ============print(getattr(s, "name")) # "张三"print(getattr(s, "age")) # 20print(getattr(s, "email", "无")) # "无"(属性不存在,返回默认值)# print(getattr(s, "email")) # ❌ AttributeError!# 获取方法并调用greet_method = getattr(s, "greet")print(greet_method()) # "你好,我是张三"# ============ setattr:设置属性 ============setattr(s, "email", "zhang@example.com")print(s.email) # "zhang@example.com"setattr(s, "age", 21)print(s.age) # 21# ============ hasattr:是否有某属性 ============print(hasattr(s, "name")) # Trueprint(hasattr(s, "phone")) # False# ============ delattr:删除属性 ============delattr(s, "email")print(hasattr(s, "email")) # False# 实际应用:动态访问属性config = {"host": "localhost", "port": 3306, "user": "admin"}class Config: passcfg = Config()for key, value in config.items(): setattr(cfg, key, value)print(cfg.host) # localhostprint(cfg.port) # 3306
6.9 vars() —— 获取属性字典
class Point: def __init__(self, x, y): self.x = x self.y = yp = Point(3, 4)print(vars(p)) # {'x': 3, 'y': 4}# 等价于 p.__dict__print(p.__dict__) # {'x': 3, 'y': 4}# 不传参数:返回当前作用域的局部变量def demo(): a = 1 b = "hello" c = [1, 2, 3] print(vars()) # {'a': 1, 'b': 'hello', 'c': [1, 2, 3]}demo()
七、输入输出类
7.1 print() —— 输出
# print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)# 基本输出print("Hello, World!")# 多个值(默认用空格分隔)print("姓名", "张三", "年龄", 25)# 输出:姓名 张三 年龄 25# 自定义分隔符print("2026", "07", "29", sep="-")# 输出:2026-07-29print("A", "B", "C", sep=" → ")# 输出:A → B → C# 自定义结尾(默认是换行 \n)print("加载中", end="")print("...", end="")print("完成!")# 输出:加载中...完成!(在同一行)# 进度条效果import timefor i in range(1, 6): print(f"\r进度:{'█' * i}{'░' * (5-i)}{i*20}%", end="", flush=True) time.sleep(0.5)print() # 最后换行# 输出到文件with open("output.txt", "w") as f: print("这行写入文件", file=f)
7.2 input() —— 输入
# input(提示信息) → 返回字符串# 基本用法name = input("请输入你的名字:")print(f"你好,{name}!")# ⚠️ input() 永远返回字符串!age = input("请输入年龄:")print(type(age)) # <class 'str'>(即使输入的是数字)# 需要数字时要转换age = int(input("请输入年龄:"))print(f"明年你就 {age + 1} 岁了")# 安全写法try: age = int(input("请输入年龄:"))except ValueError: print("❌ 请输入有效的数字!")
7.3 open() —— 文件操作
# open(file, mode='r', encoding=None)# 读文件with open("test.txt", "r", encoding="utf-8") as f: content = f.read() print(content)# 写文件with open("test.txt", "w", encoding="utf-8") as f: f.write("Hello, World!\n") f.write("你好,世界!\n")# 追加with open("test.txt", "a", encoding="utf-8") as f: f.write("追加的一行\n")# 模式说明:# "r" = 读(默认)# "w" = 写(覆盖)# "a" = 追加# "x" = 创建(文件已存在则报错)# "b" = 二进制模式# "r+" = 读写
八、作用域/变量相关
8.1 globals() 和 locals()
# globals():返回全局变量的字典# locals():返回当前作用域局部变量的字典x = 10y = "hello"def demo(): a = 1 b = 2 print("局部变量:", locals()) # {'a': 1, 'b': 2} print("全局变量:", list(globals().keys())[:5]) # 前5个全局变量名demo()# 实际应用:动态创建变量for i in range(3): globals()[f"var_{i}"] = i * 10print(var_0) # 0print(var_1) # 10print(var_2) # 20
8.2 eval() 和 exec() —— 执行代码字符串
# ⚠️ 危险!不要对不可信的输入使用!# eval():执行表达式,返回结果result = eval("2 + 3 * 4")print(result) # 14result = eval("[x**2 for x in range(5)]")print(result) # [0, 1, 4, 9, 16]# exec():执行语句(无返回值)exec("x = 42")print(x) # 42exec("""def greet(name): return f"Hello, {name}!"""")print(greet("World")) # Hello, World!# ⚠️ 安全警告# user_input = input("输入:")# eval(user_input) # 如果用户输入 __import__('os').system('rm -rf /') 就完了!
8.3 compile() —— 编译代码
# compile(source, filename, mode)# 将字符串编译为代码对象(可以用 eval/exec 执行)code = compile("2 + 3", "<string>", "eval")result = eval(code)print(result) # 5# 实际应用:预编译(重复执行时更快)expression = "x ** 2 + y ** 2"compiled = compile(expression, "<string>", "eval")for x, y in [(3, 4), (5, 12), (8, 15)]: result = eval(compiled) print(f" ({x}, {y}) → {result}")# 输出:# (3, 4) → 25# (5, 12) → 169# (8, 15) → 289
九、其他实用函数
9.1 isinstance() 已讲过,这里讲 property()
# property():创建属性(getter/setter)class Temperature: def __init__(self, celsius=0): self._celsius = celsius @property def celsius(self): return self._celsius @celsius.setter def celsius(self, value): if value < -273.15: raise ValueError("温度不能低于绝对零度!") self._celsius = value @property def fahrenheit(self): return self._celsius * 9/5 + 32t = Temperature(25)print(t.celsius) # 25(像访问属性一样)print(t.fahrenheit) # 77.0t.celsius = 100 # 设置值print(t.fahrenheit) # 212.0# t.celsius = -300 # ❌ ValueError!
9.2 super() —— 调用父类方法
class Animal: def __init__(self, name): self.name = name def speak(self): return f"{self.name}发出声音"class Dog(Animal): def __init__(self, name, breed): super().__init__(name) # 调用父类的 __init__ self.breed = breed def speak(self): parent_speak = super().speak() # 调用父类的 speak return f"{parent_speak}:汪汪!"d = Dog("旺财", "金毛")print(d.name) # 旺财(父类设置的)print(d.breed) # 金毛(子类设置的)print(d.speak()) # 旺财发出声音:汪汪!
9.3 staticmethod() 和 classmethod()
class MathUtils: @staticmethod def add(a, b): """静态方法:不需要访问类或实例""" return a + b @classmethod def from_string(cls, s): """类方法:第一个参数是类本身""" parts = s.split(",") return cls(*[int(x) for x in parts])# 静态方法:通过类或实例都能调用print(MathUtils.add(3, 5)) # 8# 类方法:常用于替代构造函数# (这里简化演示)
9.4 object() —— 所有类的基类
# object 是 Python 中所有类的基类class MyClass: pass# 等价于class MyClass(object): passprint(isinstance(MyClass(), object)) # True
9.5 memoryview() —— 内存视图
# 在不复制数据的情况下查看/修改字节数据data = bytearray(b"Hello, World!")mv = memoryview(data)print(mv[0]) # 72('H' 的 ASCII)print(bytes(mv[0:5])) # b'Hello'# 通过 memoryview 修改原数据(不复制)mv[0] = 104 # 'h'print(data) # bytearray(b'hello, World!')(原数据被修改了)
9.6 breakpoint() —— 调试断点(Python 3.7+)
def calculate(x, y): result = x + y breakpoint() # 程序会在这里暂停,进入调试器 return result * 2# calculate(3, 4) # 运行时会进入 pdb 调试器# 在调试器中可以查看变量、单步执行等
9.7 import() —— 动态导入
# 通常用 import 语句,但有时需要动态导入module_name = "math"math_module = __import__(module_name)print(math_module.sqrt(16)) # 4.0# 更推荐的方式:import importlibmath_module = importlib.import_module("math")print(math_module.pi) # 3.14159...
十、按使用频率分类总结
🔥 每天都用(必须熟练)
| | |
|---|
print() | | |
len() | | |
range() | | |
type() | | |
int()/float()/str() | | |
list()/dict()/set() | | |
input() | | |
open() | | |
enumerate() | | |
sorted() | | |
max()/min()/sum() | | |
isinstance() | | |
abs() | | |
round() | | |
⭐ 经常用(应该掌握)
| |
|---|
zip() | |
map() | |
filter() | |
all()/any() | |
reversed() | |
bool() | |
chr()/ord() | |
divmod() | |
pow() | |
repr() | |
dir() | |
getattr()/setattr() | |
super() | |
💡 偶尔用(了解即可)
| |
|---|
id() | |
hash() | |
callable() | |
iter()/next() | |
globals()/locals() | |
eval()/exec() | |
compile() | |
memoryview() | |
breakpoint() | |
slice() | |
ascii() | |
complex() | |
bytes()/bytearray() | |
十一、综合实战
11.1 学生成绩分析系统
# 综合运用:input, print, len, max, min, sum, sorted, enumerate, zip, round, all, anydef analyze_scores(): """学生成绩分析""" # 数据 students = ["张三", "李四", "王五", "赵六", "钱七"] subjects = ["语文", "数学", "英语"] scores = [ [92, 85, 78], # 张三 [88, 92, 95], # 李四 [76, 68, 82], # 王五 [95, 99, 91], # 赵六 [60, 55, 72], # 钱七 ] print("=" * 50) print("📊 学生成绩分析报告") print("=" * 50) # 1. 每个学生的总分和平均分 print("\n【个人成绩】") print(f"{'姓名':<6}{'语文':>4}{'数学':>4}{'英语':>4}{'总分':>6}{'平均':>6}") print("-" * 40) averages = [] for i, (name, score_list) in enumerate(zip(students, scores)): total = sum(score_list) avg = round(total / len(score_list), 1) averages.append(avg) print(f"{name:<6}{score_list[0]:>4}{score_list[1]:>4}{score_list[2]:>4}{total:>6}{avg:>6}") # 2. 排名 print("\n【排名】") ranked = sorted(zip(students, averages), key=lambda x: x[1], reverse=True) for rank, (name, avg) in enumerate(ranked, 1): medal = "🥇🥈🥉"[rank-1] if rank <= 3 else " " print(f" {medal} 第{rank}名:{name}(平均 {avg} 分)") # 3. 各科统计 print("\n【各科统计】") for j, subject in enumerate(subjects): subject_scores = [scores[i][j] for i in range(len(students))] print(f" {subject}:最高 {max(subject_scores)}," f"最低 {min(subject_scores)}," f"平均 {round(sum(subject_scores)/len(subject_scores), 1)}") # 4. 及格情况 print("\n【及格分析】") for name, score_list in zip(students, scores): failed = [subjects[j] for j, s in enumerate(score_list) if s < 60] if failed: print(f" ⚠️ {name} 不及格科目:{', '.join(failed)}") else: print(f" ✅ {name} 全部及格") # 5. 整体判断 all_pass = all(all(s >= 60 for s in score_list) for score_list in scores) any_full = any(all(s >= 90 for s in score_list) for score_list in scores) print(f"\n【总结】") print(f" 全部及格?{'是'if all_pass else'否'}") print(f" 有全优生?{'是'if any_full else'否'}") print("=" * 50)analyze_scores()
输出:
==================================================📊 学生成绩分析报告==================================================【个人成绩】姓名 语文 数学 英语 总分 平均----------------------------------------张三 92 85 78 255 85.0李四 88 92 95 275 91.7王五 76 68 82 226 75.3赵六 95 99 91 285 95.0钱七 60 55 72 187 62.3【排名】 🥇 第1名:赵六(平均 95.0 分) 🥈 第2名:李四(平均 91.7 分) 🥉 第3名:张三(平均 85.0 分) 第4名:王五(平均 75.3 分) 第5名:钱七(平均 62.3 分)【各科统计】 语文:最高 95,最低 60,平均 82.2 数学:最高 99,最低 55,平均 79.8 英语:最高 95,最低 72,平均 83.6【及格分析】 ✅ 张三 全部及格 ✅ 李四 全部及格 ✅ 王五 全部及格 ✅ 赵六 全部及格 ⚠️ 钱七 不及格科目:数学【总结】 全部及格?否 有全优生?是==================================================
11.2 密码强度检测器
# 综合运用:len, any, all, ord, chr, isinstance, printdef check_password_strength(password): """检测密码强度""" if not isinstance(password, str): return "❌ 密码必须是字符串" # 基本检查 checks = { "长度≥8": len(password) >= 8, "包含大写字母": any(c.isupper() for c in password), "包含小写字母": any(c.islower() for c in password), "包含数字": any(c.isdigit() for c in password), "包含特殊字符": any(not c.isalnum() for c in password), "不含空格": all(c != " " for c in password), } # 计算得分 score = sum(checks.values()) # 显示结果 print(f"\n🔐 密码强度检测:{'*' * len(password)}") print("-" * 35) for rule, passed in checks.items(): icon = "✅" if passed else "❌" print(f" {icon}{rule}") print("-" * 35) if score <= 2: level = "💀 极弱" elif score <= 3: level = "⚠️ 较弱" elif score <= 4: level = "🔒 中等" elif score <= 5: level = "🔐 较强" else: level = "🛡️ 极强" print(f" 得分:{score}/6 → {level}") return level# 测试check_password_strength("abc")check_password_strength("Abc12345")check_password_strength("MyP@ss2026!")
十二、查看所有内置函数
# 在 Python 交互模式中:import builtinsprint(dir(builtins))# 或者查看文档:help(print) # 查看 print 的详细文档help(sorted) # 查看 sorted 的详细文档# 查看某个函数的签名import inspectprint(inspect.signature(sorted))# (iterable, /, *, key=None, reverse=False)