【面试宝典】Python 全栈面试实战
实验环境 :华为云 ECS 服务器 ecs-5d9b-0001 (119.8.30.110)
操作系统 :Ubuntu 24.04.4 LTS (Linux 6.8.0-106-generic)
Python版本 :3.12.3
实验时间 :2026-07-05
实验方式:所有代码均在 ECS 服务器上真实上机运行
目录
| 序号 | 章节 | 知识点 |
|---|---|---|
| 01 | [Python 数据类型](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试) | 数据类型创建与操作、面试题 |
| 02 | [Python 函数和高阶函数](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试) | 函数定义、高阶函数、装饰器 |
| 03 | [Python 包与模块、异常处理](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试) | 模块导入、异常处理机制 |
| 04 | [Python 面向对象](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试) | OOP三大特性、魔术方法、内存管理 |
| 05 | [Python 并发编程](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试) | 线程、协程、锁、GIL |
| 06 | [Python 设计模式](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试) | 单例、工厂、装饰器、观察者等 |
| 07 | [Python 数据库](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试) | SQLite/Redis/MongoDB |
| 08 | [Python Web 框架](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试) | Flask/Django/FastAPI |
| 09 | [Python 爬虫](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试) | HTTP请求、HTML解析、数据存储 |
| 10 | [Python 自动化测试](#序号 章节 知识点 01 Python 数据类型 数据类型创建与操作、面试题 02 Python 函数和高阶函数 函数定义、高阶函数、装饰器 03 Python 包与模块、异常处理 模块导入、异常处理机制 04 Python 面向对象 OOP三大特性、魔术方法、内存管理 05 Python 并发编程 线程、协程、锁、GIL 06 Python 设计模式 单例、工厂、装饰器、观察者等 07 Python 数据库 SQLite/Redis/MongoDB 08 Python Web 框架 Flask/Django/FastAPI 09 Python 爬虫 HTTP请求、HTML解析、数据存储 10 Python 自动化测试 unittest/Mock/接口测试/Web测试) | unittest/Mock/接口测试/Web测试 |
服务器环境信息
主机名: ecs-5d9b-0001
操作系统: Ubuntu 24.04.4 LTS
内核: Linux 6.8.0-106-generic x86_64
Python: 3.12.3
CPU: 8vCPUs (c6s.2xlarge.2)
内存: 16GiB
弹性公网IP: 119.8.30.110
私有IP: 192.168.0.186
02 Python 函数和高阶函数
知识点
1.Python中函数的定义与使用 2.Python中常见函数以及高阶函数的使用与技巧
简介
函数是Python中代码复用的基本单元。Python支持多种参数类型(位置参数、关键字参数、默认参数、可变参数)、高阶函数(map/filter/reduce/sorted)、闭包和装饰器。
实验源码
python
#!/usr/bin/env python3
"""
【面试宝典】Python 函数和高阶函数
知识点: 1.Python中函数的定义与使用 2.Python中常见函数以及高阶函数的使用与技巧
"""
print("=" * 70)
print("【面试宝典】Python 函数和高阶函数")
print("=" * 70)
# ============================================================
# 1. 函数基础
# ============================================================
print("\n" + "=" * 70)
print("1. 函数基础:定义、参数、返回值")
print("=" * 70)
# 1.1 基本函数定义
print("\n--- 1.1 基本函数定义 ---")
def greet(name, greeting="Hello"):
"""带默认参数的函数"""
return f"{greeting}, {name}!"
print(greet("Alice"))
print(greet("Bob", greeting="Hi"))
print(f"greet.__doc__ = {greet.__doc__}")
print(f"greet.__name__ = {greet.__name__}")
# 1.2 参数类型
print("\n--- 1.2 参数类型 ---")
# 位置参数
def positional(a, b, c):
return f"a={a}, b={b}, c={c}"
print(f"positional(1, 2, 3) = {positional(1, 2, 3)}")
# 关键字参数
print(f"positional(c=3, a=1, b=2) = {positional(c=3, a=1, b=2)}")
# *args 可变位置参数
def var_positional(*args):
return f"args = {args}, type = {type(args).__name__}"
print(f"var_positional(1, 2, 3, 4) = {var_positional(1, 2, 3, 4)}")
# **kwargs 可变关键字参数
def var_keyword(**kwargs):
return f"kwargs = {kwargs}, type = {type(kwargs).__name__}"
print(f"var_keyword(x=1, y=2) = {var_keyword(x=1, y=2)}")
# 混合参数
def mixed(a, b, *args, **kwargs):
return f"a={a}, b={b}, args={args}, kwargs={kwargs}"
print(f"mixed(1, 2, 3, 4, x=5, y=6) = {mixed(1, 2, 3, 4, x=5, y=6)}")
# 1.3 仅关键字参数 (Python 3+)
print("\n--- 1.3 仅关键字参数 ---")
def keyword_only(a, b, *, c, d):
return f"a={a}, b={b}, c={c}, d={d}"
print(f"keyword_only(1, 2, c=3, d=4) = {keyword_only(1, 2, c=3, d=4)}")
try:
keyword_only(1, 2, 3, 4)
except TypeError as e:
print(f"keyword_only(1, 2, 3, 4) -> TypeError: {e}")
# 1.4 仅位置参数 (Python 3.8+)
print("\n--- 1.4 仅位置参数 (Python 3.8+) ---")
def positional_only(a, b, /, c, d):
return f"a={a}, b={b}, c={c}, d={d}"
print(f"positional_only(1, 2, c=3, d=4) = {positional_only(1, 2, c=3, d=4)}")
# 1.5 返回多个值
print("\n--- 1.5 返回多个值 ---")
def min_max(nums):
return min(nums), max(nums), sum(nums) / len(nums)
result = min_max([1, 2, 3, 4, 5])
print(f"min_max([1,2,3,4,5]) = {result}")
mn, mx, avg = min_max([1, 2, 3, 4, 5])
print(f"解包: min={mn}, max={mx}, avg={avg}")
# ============================================================
# 2. 高阶函数
# ============================================================
print("\n" + "=" * 70)
print("2. 高阶函数:map, filter, reduce, sorted, lambda")
print("=" * 70)
# 2.1 lambda 匿名函数
print("\n--- 2.1 lambda 匿名函数 ---")
square = lambda x: x ** 2
print(f"square(5) = {square(5)}")
add = lambda x, y: x + y
print(f"add(3, 5) = {add(3, 5)}")
# 2.2 map
print("\n--- 2.2 map函数 ---")
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, nums))
print(f"map(lambda x: x**2, {nums}) = {squared}")
# map 多个可迭代对象
list1 = [1, 2, 3]
list2 = [10, 20, 30]
added = list(map(lambda x, y: x + y, list1, list2))
print(f"map(lambda x,y: x+y, {list1}, {list2}) = {added}")
# 2.3 filter
print("\n--- 2.3 filter函数 ---")
nums = list(range(1, 11))
evens = list(filter(lambda x: x % 2 == 0, nums))
print(f"filter(even, {nums}) = {evens}")
# 过滤None和空值
data = [0, 1, '', 'hello', None, False, [], [1], {}]
truthy = list(filter(None, data))
print(f"filter(None, {data}) = {truthy}")
# 2.4 reduce
print("\n--- 2.4 reduce函数 ---")
from functools import reduce
nums = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, nums)
print(f"reduce(multiply, {nums}) = {product}")
# 求最大值
maximum = reduce(lambda x, y: x if x > y else y, nums)
print(f"reduce(max, {nums}) = {maximum}")
# reduce 带初始值
total = reduce(lambda x, y: x + y, nums, 100)
print(f"reduce(add, {nums}, 100) = {total}")
# 2.5 sorted
print("\n--- 2.5 sorted函数 ---")
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78},
]
by_score = sorted(students, key=lambda s: s["score"], reverse=True)
print(f"按分数降序: {[s['name'] for s in by_score]}")
# 多级排序
data = [("Alice", 85), ("Bob", 92), ("Alice", 90), ("Bob", 85)]
multi_sorted = sorted(data, key=lambda x: (x[0], -x[1]))
print(f"多级排序(名字升序,分数降序): {multi_sorted}")
# 2.6 enumerate
print("\n--- 2.6 enumerate函数 ---")
fruits = ['apple', 'banana', 'cherry']
for idx, fruit in enumerate(fruits, start=1):
print(f" {idx}. {fruit}")
# 2.7 zip
print("\n--- 2.7 zip函数 ---")
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f" {name}: {score}")
# 不等长zip (itertools.zip_longest)
from itertools import zip_longest
short = [1, 2, 3]
long = ['a', 'b', 'c', 'd', 'e']
zipped = list(zip_longest(short, long, fillvalue='?'))
print(f"zip_longest({short}, {long}) = {zipped}")
# ============================================================
# 3. 闭包与装饰器
# ============================================================
print("\n" + "=" * 70)
print("3. 闭包与装饰器")
print("=" * 70)
# 3.1 闭包
print("\n--- 3.1 闭包 ---")
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
c = make_counter()
print(f"c() = {c()}") # 1
print(f"c() = {c()}") # 2
print(f"c() = {c()}") # 3
# 3.2 装饰器基础
print("\n--- 3.2 装饰器基础 ---")
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
print(f" [timer] {func.__name__} 耗时: {elapsed:.6f}s")
return result
return wrapper
@timer
def slow_function(n):
time.sleep(0.1)
return sum(range(n))
result = slow_function(100000)
print(f" slow_function(100000) = {result}")
# 3.3 带参数的装饰器
print("\n--- 3.3 带参数的装饰器 ---")
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
results = []
for i in range(n):
results.append(func(*args, **kwargs))
return results
return wrapper
return decorator
@repeat(3)
def say_hello(name):
return f"Hello, {name}!"
print(f"say_hello('Alice') = {say_hello('Alice')}")
# 3.4 functools.wraps
print("\n--- 3.4 functools.wraps ---")
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@my_decorator
def my_func():
"""这是my_func的文档"""
pass
print(f"my_func.__name__ = {my_func.__name__}") # my_func (不是wrapper)
print(f"my_func.__doc__ = {my_func.__doc__}")
# ============================================================
# 4. 常见面试题
# ============================================================
print("\n" + "=" * 70)
print("4. 常见面试题")
print("=" * 70)
# 面试题1: 生成器 vs 列表推导式
print("\n--- 面试题1: 生成器 vs 列表推导式 ---")
import sys
lst = [x ** 2 for x in range(1000)]
gen = (x ** 2 for x in range(1000))
print(f"列表内存: {sys.getsizeof(lst)} bytes")
print(f"生成器内存: {sys.getsizeof(gen)} bytes")
# yield 生成器函数
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(f"fibonacci(10) = {list(fibonacci(10))}")
# 面试题2: 偏函数
print("\n--- 面试题2: 偏函数 (functools.partial) ---")
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(f"square(5) = {square(5)}")
print(f"cube(3) = {cube(3)}")
# 面试题3: *和**解包
print("\n--- 面试题3: *和**解包 ---")
def add(a, b, c):
return a + b + c
args = [1, 2, 3]
print(f"add(*[1,2,3]) = {add(*args)}")
kwargs = {"a": 1, "b": 2, "c": 3}
print(f"add(**{{'a':1,'b':2,'c':3}}) = {add(**kwargs)}")
# 列表解包
first, *rest = [1, 2, 3, 4, 5]
print(f"first, *rest = [1,2,3,4,5] -> first={first}, rest={rest}")
# 面试题4: 递归
print("\n--- 面试题4: 递归与尾递归 ---")
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(f"factorial(5) = {factorial(5)}")
# 使用lru_cache优化递归
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(f"fib(50) with lru_cache = {fib(50)}")
print(f"fib.cache_info() = {fib.cache_info()}")
# 面试题5: 函数作为一等公民
print("\n--- 面试题5: 函数作为一等公民 ---")
operations = {
'add': lambda x, y: x + y,
'sub': lambda x, y: x - y,
'mul': lambda x, y: x * y,
'div': lambda x, y: x / y if y != 0 else None,
}
for name, op in operations.items():
print(f" {name}(10, 3) = {op(10, 3)}")
# 面试题6: map/filter/reduce vs 列表推导式
print("\n--- 面试题6: 性能对比 ---")
nums = list(range(1000))
start = time.time()
result1 = list(map(lambda x: x**2, filter(lambda x: x%2==0, nums)))
t1 = time.time() - start
start = time.time()
result2 = [x**2 for x in nums if x%2==0]
t2 = time.time() - start
print(f"map+filter: {t1:.6f}s, len={len(result1)}")
print(f"列表推导式: {t2:.6f}s, len={len(result2)}")
print(f"结果一致: {result1 == result2}")
print("结论: 列表推导式通常更快更Pythonic")
print("\n" + "=" * 70)
print("函数和高阶函数实验完成!")
print("=" * 70)
上机输出(ECS服务器实际运行结果)
======================================================================
【面试宝典】Python 函数和高阶函数
======================================================================
======================================================================
1. 函数基础:定义、参数、返回值
======================================================================
--- 1.1 基本函数定义 ---
Hello, Alice!
Hi, Bob!
greet.__doc__ = 带默认参数的函数
greet.__name__ = greet
--- 1.2 参数类型 ---
positional(1, 2, 3) = a=1, b=2, c=3
positional(c=3, a=1, b=2) = a=1, b=2, c=3
var_positional(1, 2, 3, 4) = args = (1, 2, 3, 4), type = tuple
var_keyword(x=1, y=2) = kwargs = {'x': 1, 'y': 2}, type = dict
mixed(1, 2, 3, 4, x=5, y=6) = a=1, b=2, args=(3, 4), kwargs={'x': 5, 'y': 6}
--- 1.3 仅关键字参数 ---
keyword_only(1, 2, c=3, d=4) = a=1, b=2, c=3, d=4
keyword_only(1, 2, 3, 4) -> TypeError: keyword_only() takes 2 positional arguments but 4 were given
--- 1.4 仅位置参数 (Python 3.8+) ---
positional_only(1, 2, c=3, d=4) = a=1, b=2, c=3, d=4
--- 1.5 返回多个值 ---
min_max([1,2,3,4,5]) = (1, 5, 3.0)
解包: min=1, max=5, avg=3.0
======================================================================
2. 高阶函数:map, filter, reduce, sorted, lambda
======================================================================
--- 2.1 lambda 匿名函数 ---
square(5) = 25
add(3, 5) = 8
--- 2.2 map函数 ---
map(lambda x: x**2, [1, 2, 3, 4, 5]) = [1, 4, 9, 16, 25]
map(lambda x,y: x+y, [1, 2, 3], [10, 20, 30]) = [11, 22, 33]
--- 2.3 filter函数 ---
filter(even, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) = [2, 4, 6, 8, 10]
filter(None, [0, 1, '', 'hello', None, False, [], [1], {}]) = [1, 'hello', [1]]
--- 2.4 reduce函数 ---
reduce(multiply, [1, 2, 3, 4, 5]) = 120
reduce(max, [1, 2, 3, 4, 5]) = 5
reduce(add, [1, 2, 3, 4, 5], 100) = 115
--- 2.5 sorted函数 ---
按分数降序: ['Bob', 'Alice', 'Charlie']
多级排序(名字升序,分数降序): [('Alice', 90), ('Alice', 85), ('Bob', 92), ('Bob', 85)]
--- 2.6 enumerate函数 ---
1. apple
2. banana
3. cherry
--- 2.7 zip函数 ---
Alice: 85
Bob: 92
Charlie: 78
zip_longest([1, 2, 3], ['a', 'b', 'c', 'd', 'e']) = [(1, 'a'), (2, 'b'), (3, 'c'), ('?', 'd'), ('?', 'e')]
======================================================================
3. 闭包与装饰器
======================================================================
--- 3.1 闭包 ---
c() = 1
c() = 2
c() = 3
--- 3.2 装饰器基础 ---
[timer] slow_function 耗时: 0.102493s
slow_function(100000) = 4999950000
--- 3.3 带参数的装饰器 ---
say_hello('Alice') = ['Hello, Alice!', 'Hello, Alice!', 'Hello, Alice!']
--- 3.4 functools.wraps ---
my_func.__name__ = my_func
my_func.__doc__ = 这是my_func的文档
======================================================================
4. 常见面试题
======================================================================
--- 面试题1: 生成器 vs 列表推导式 ---
列表内存: 8856 bytes
生成器内存: 200 bytes
fibonacci(10) = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
--- 面试题2: 偏函数 (functools.partial) ---
square(5) = 25
cube(3) = 27
--- 面试题3: *和**解包 ---
add(*[1,2,3]) = 6
add(**{'a':1,'b':2,'c':3}) = 6
first, *rest = [1,2,3,4,5] -> first=1, rest=[2, 3, 4, 5]
--- 面试题4: 递归与尾递归 ---
factorial(5) = 120
fib(50) with lru_cache = 12586269025
fib.cache_info() = CacheInfo(hits=48, misses=51, maxsize=None, currsize=51)
--- 面试题5: 函数作为一等公民 ---
add(10, 3) = 13
sub(10, 3) = 7
mul(10, 3) = 30
div(10, 3) = 3.3333333333333335
--- 面试题6: 性能对比 ---
map+filter: 0.000126s, len=500
列表推导式: 0.000056s, len=500
结果一致: True
结论: 列表推导式通常更快更Pythonic
======================================================================
函数和高阶函数实验完成!
======================================================================