(接上篇)这一篇我们进入 Python 面试中硬核的两大块:内存管理与并发编程、面向对象设计思想,包括深拷贝浅拷贝、垃圾回收、循环引用、 内存泄漏、GIL、多进程、线程池共 17 个高频问答。这里应该是Python部分最重要、最高频的模块之一。
五、内存管理与性能
31. Python的深拷贝与浅拷贝?
在Python中,赋值 a = b 只是增加了对象的引用计数,a 和 b 指向同一个对象。
浅拷贝(Shallow Copy)
创建一个新对象,但内部元素仍然引用原对象的子对象。
import copy
a = [[1, 2], [3, 4]]
b = copy.copy(a) # 浅拷贝
print(a is b) # False(外层容器不同)
print(a[0] is b[0]) # True!(内层子对象相同)
# 修改内层子对象会影响双方
a[0][0] = 999
print(b[0][0]) # 999(b也受到影响!)
常见的浅拷贝方式:list()、dict()、copy.copy()、切片 [:]。
深拷贝(Deep Copy)
递归地拷贝所有子对象,新旧对象完全独立。
a = [[1, 2], [3, 4]]
c = copy.deepcopy(a) # 深拷贝
print(a is c) # False
print(a[0] is c[0]) # False(内层子对象也不同!)
a[0][0] = 999
print(c[0][0]) # 1(c不受影响)
选择指南
| |
|---|
| |
| 对象只包含不可变元素(int, str, tuple),不需要独立子对象 |
| |
32. Python的垃圾回收机制
Python使用三种机制协同管理内存:
1. 引用计数(主机制)
2. 标记-清除(处理循环引用)
3. 分代回收(提升效率)
- 主要扫描0代(年轻对象),因为大多数对象生命周期短。
import gc
print(gc.get_threshold()) # 默认 (700, 10, 10)
gc.set_threshold(1000, 10, 5) # 自定义阈值
gc.collect() # 手动触发垃圾回收
33. Python中引用计数原理与循环引用
引用计数规则
import sys
a = [1, 2, 3] # 引用计数 = 1
b = a # 引用计数 = 2
del b # 引用计数 = 1
c = {'key': a} # 引用计数 = 2
del c['key'] # 引用计数 = 1
del a # 引用计数 = 0 → 对象被销毁
sys.getrefcount(obj) 可查看引用计数(结果比实际多1,因为调用本身增加了一个临时引用)。
循环引用问题
class Node:
def __init__(self, value):
self.value = value
self.next = None
node1 = Node(1)
node2 = Node(2)
node1.next = node2
node2.next = node1 # 循环引用!
del node1
del node2
# 此时两个对象的引用计数都不为0(互相引用)
# — 只能由垃圾回收器的标记-清除机制处理
解决方案:
# 1. 手动断开
node1.next = None
node2.next = None
# 2. 使用弱引用
import weakref
node1.next = weakref.ref(node2) # 弱引用不增加引用计数
# 3. 手动触发GC
import gc
gc.collect()
34. Python中什么情况下会产生内存泄漏?
虽然Python有自动垃圾回收,以下情况仍可导致内存泄漏:
| | |
|---|
| 循环引用 | | |
| 全局变量/缓存无限增长 | | 使用 functools.lru_cache(maxsize=N);定期清理 |
| 未释放外部资源 | | |
| 闭包持有大对象 | | |
| C扩展泄漏 | | 检查库文档,及时 del + gc.collect() |
__del__ 异常 | | |
检测工具:
import tracemalloc
tracemalloc.start()
# ... 运行代码 ...
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:10]:
print(stat)
35. 有哪些提高Python运行效率的方法?
代码层面
# 1. 使用推导式代替循环
squares = [i**2 for i in range(1000)] # 比 for+append 快
# 2. 字符串拼接用 join 而非 +
result = ''.join(list_of_strings) # 比 += 快
# 3. 使用局部变量(访问更快)
def fast():
local_var = global_var # 缓存在局部
for i in range(1000):
process(local_var)
# 4. 使用生成器处理大数据(节省内存)
sum(x**2 for x in range(10**8))
# 5. 合理使用集合/字典进行查找(O(1) vs 列表的O(n))
valid = set(['a', 'b', 'c'])
if item in valid: # O(1)
pass
工具层面
| |
|---|
| NumPy/Pandas | |
| Cython | |
| Numba | |
| 多进程 | multiprocessing |
| 异步编程 | asyncio |
| PyPy | |
性能分析工具
# cProfile:标准库性能分析器
python -m cProfile -o output.prof script.py
# line_profiler:逐行分析
# memory_profiler:内存分析
六、并发编程
36. Python里的多线程与全局解释器锁GIL
GIL(Global Interpreter Lock)
GIL是CPython解释器中的一个互斥锁,保证同一时刻只有一个线程执行Python字节码。
为什么需要GIL?
- CPython的内存管理使用引用计数。如果两个线程同时修改同一个对象的引用计数(如
a = b 操作),可能导致计数错乱。加锁保护每个引用计数操作太慢,于是用一个全局锁。 - 保护CPython内部数据结构,简化了解释器的实现。
GIL的释放时机(这是理解"什么时候用线程"的关键):
| |
|---|
| socket.read(), time.sleep(), file.read() — 解释器主动释放 GIL,让其他线程运行 |
| Python 3.2+ 基于超时机制:线程持有 GIL 约 5ms 后强制释放(sys.setswitchinterval 可调) |
| NumPy 等 C 扩展在执行计算前可以通过 Py_BEGIN_ALLOW_THREADS 显式释放 GIL |
I/O密集多线程有效的原理:线程 A 发网络请求 → 主动释放 GIL → 线程 B 获得 GIL 发第二个请求 → B 也释放 GIL → A 的 I/O 完成后重新获取 GIL。虽然只有一个核跑 Python,但 I/O 等待期间可以切换,多个 I/O 操作在"并行等待"。
GIL的影响
# I/O密集型:多线程有效
import threading
def io_task():
# 网络请求等I/O操作
time.sleep(1) # 此时GIL被释放
# CPU密集型:多线程无效,应用多进程
from multiprocessing import Pool
def cpu_task(n):
return sum(i * i for i in range(n))
with Pool(4) as p:
results = p.map(cpu_task, [10**6] * 10)
绕过GIL的方法
- 多进程(
multiprocessing、concurrent.futures.ProcessPoolExecutor) - 使用C扩展
- 使用其他Python实现:Jython(JVM)、IronPython(.NET)无 GIL;Python 3.13 起实验性支持 free-threaded 模式(编译选项
--disable-gil),3.14 正式支持(2025年10月发布)。代价:单线程性能下降约 10%,引用计数改用线程安全的偏置引用计数 - 异步编程(
asyncio 单线程协程,不是真正并行但高效处理 I/O)
asyncio 事件循环机制:asyncio 在单线程中通过事件循环调度协程。每次 await 让出控制权,事件循环检查哪些 I/O 已完成(通过操作系统的 epoll/kqueue/IOCP),恢复对应的协程。本质是协作式多任务——协程主动 await 让出,而非操作系统抢占式调度。这使得 asyncio 能处理数万并发连接,但单个协程中的 CPU 密集操作会阻塞整个事件循环——解法是 await asyncio.to_thread(cpu_task) 丢给线程池。
Python 并发选型指南
CPU 密集型 → 多进程(multiprocessing)或 C 扩展(NumPy/Numba)
I/O 密集型
├── 并发 < 100,逻辑简单 → 多线程(threading)
└── 并发 > 1000 → asyncio(协程)
1000 线程也可跑但上下文切换开销大,不如协程高效
37. Python多进程中的fork和spawn模式有什么区别?
| | |
|---|
| 原理 | | |
| 启动速度 | | |
| 资源继承 | | |
| 安全性 | | |
| 平台支持 | | Windows(默认)、MacOS(默认)、Unix |
| Windows支持 | | |
import multiprocessing as mp
# 在Unix上可以设置启动方式
mp.set_start_method('fork') # 或 'spawn'、'forkserver'
# 推荐:用 spawn 确保跨平台兼容
if __name__ == '__main__':
mp.set_start_method('spawn', force=True)
38. 线程池与进程池的区别是什么?
| | |
|---|
| 适用任务 | | |
| 受GIL影响 | | |
| 资源共享 | | |
| 上下文切换开销 | | |
| 创建销毁开销 | | |
| 通信方式 | | |
| Python实现 | concurrent.futures.ThreadPoolExecutor | concurrent.futures.ProcessPoolExecutor |
选择指南:
39. multiprocessing模块怎么使用?
multiprocessing 模块的核心组件:
from multiprocessing import Process, Pool, Queue, Pipe, Lock, Manager
import time
# 1. Process:创建独立进程
def worker(name):
print(f'Worker {name} started')
time.sleep(1)
print(f'Worker {name} finished')
if __name__ == '__main__':
p = Process(target=worker, args=('A',))
p.start()
p.join() # 等待进程结束
# 2. Pool:进程池并发
def square(x):
return x * x
if __name__ == '__main__':
with Pool(4) as p:
results = p.map(square, [1, 2, 3, 4, 5, 6])
print(results) # [1, 4, 9, 16, 25, 36]
# 3. Queue:进程间安全通信
def producer(q):
q.put('Hello from child process')
if __name__ == '__main__':
q = Queue()
p = Process(target=producer, args=(q,))
p.start()
print(q.get()) # 主进程收取数据
p.join()
# 4. Manager:共享复杂Python对象
def update(shared_dict, key, value):
shared_dict[key] = value
if __name__ == '__main__':
with Manager() as manager:
shared_dict = manager.dict()
processes = [Process(target=update, args=(shared_dict, i, i*i)) for i in range(4)]
for p in processes:
p.start()
for p in processes:
p.join()
print(shared_dict) # {0: 0, 1: 1, 2: 4, 3: 9}
关键组件速查:Process、Pool、Queue、Pipe、Lock、Semaphore、Event、Value、Array、Manager。
40. ProcessPoolExecutor怎么使用?
concurrent.futures.ProcessPoolExecutor 提供了比 multiprocessing.Pool 更高级的接口。
from concurrent.futures import ProcessPoolExecutor
import time
def cpu_task(n):
time.sleep(1) # 模拟计算
return n * n
if __name__ == '__main__':
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
with ProcessPoolExecutor(max_workers=4) as executor:
# 方法1:submit + Future
futures = [executor.submit(cpu_task, num) for num in numbers]
results = [f.result() for f in futures]
# 方法2:map(保持输入顺序)
results = list(executor.map(cpu_task, numbers))
print(results) # [1, 4, 9, 16, 25, 36, 49, 64]
ProcessPoolExecutor vs multiprocessing.Pool:
七、OOP设计思想
41. Python中的封装(Encapsulation)思想
封装是面向对象编程的核心原则之一,通过隐藏内部实现细节,只暴露必要的接口。
Python中的访问控制(依赖命名约定)
| | |
|---|
| 公有(Public) | name | |
| 受保护(Protected) | _name | |
| 私有(Private) | __name | 通过名称重整(name mangling)变为 _ClassName__name |
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner # 公有
self.__balance = balance # 私有
@property
def balance(self):
"""getter:对外提供安全的访问方式"""
returnself.__balance
@balance.setter
def balance(self, amount):
"""setter:在修改时进行验证"""
if amount < 0:
raise ValueError("余额不能为负")
self.__balance = amount
account = BankAccount("Alice", 1000)
print(account.balance) # 1000(通过property访问)
account.balance = 2000 # 通过setter修改
# account.__balance # AttributeError!
注意:Python的"私有"并非强制隔离(可通过 account._BankAccount__balance 强行访问),这是一种"大家都是成年人"的设计哲学。
42. Python中的继承(Inheritance)思想
继承允许子类复用父类的属性和方法,同时可以扩展或重写。
基本继承
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self): # 方法重写(Override)
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
多重继承与MRO
Python 使用 C3 线性化算法计算 MRO(Method Resolution Order,方法解析顺序),决定多继承时属性查找的先后顺序。
核心原则:① 子类优先于父类 ② 父类顺序按定义从左到右 ③ 所有祖先只出现一次(在最后出现位置)。
菱形继承(Diamond Problem):当 D 继承 B 和 C,B 和 C 都继承 A——D 中应该只保留一份 A。C3 算法通过拓扑排序 + 一致性检查解决了这个问题:
class A:
def who(self): return "A"
class B(A):
def who(self): return "B"
class C(A):
def who(self): return "C"
class D(B, C): # D 继承 B 和 C
pass
print(D.mro()) # D → B → C → A → object
print(D().who()) # "B" —— B 在 C 前面
super() 沿 MRO 链条调用下一个类,而不是固定调用"父类"。在 D 中调用 super() 会顺着 D→B→C→A 依次调用。这也是为什么 super() 在多继承中能正确工作——它是针对 MRO 的,不是针对父类的。
面试追问:如果写 class D(C, B) 会怎样? MRO 变成 D→C→B→A,D().who() 返回 "C"。顺序由定义时的基类排序决定,完全不同。
class Person:
def __init__(self, name):
self.name = name
class Employee(Person):
def __init__(self, name, employee_id):
super().__init__(name) # 调用父类__init__
self.employee_id = employee_id
43. Python中的多态(Polymorphism)思想
多态允许不同类的对象对同一消息做出不同的响应,即"一个接口,多种实现"。
# Python的鸭子类型(Duck Typing):
# "如果它走起来像鸭子,叫起来像鸭子,那它就是鸭子"
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
class Duck:
def speak(self):
return "Quack!"
# 多态:统一的接口,不同的行为
def animal_sound(animal):
print(animal.speak())
animal_sound(Dog()) # Woof!
animal_sound(Cat()) # Meow!
animal_sound(Duck()) # Quack!
鸭子类型:Python不要求对象继承自特定基类,只要对象实现了所需的方法(如 speak()),就能以多态方式使用。这比强类型语言的接口/抽象类更加灵活。
44. Python中的耦合和解耦的代码设计思想
耦合(Coupling):模块间的依赖程度。高耦合意味着一个模块的修改会牵动其他模块。
解耦(Decoupling):降低模块间的依赖,使系统更易于维护和扩展。
解耦的三种常见方法
1. 依赖注入
class Database:
def connect(self):
print("Connecting to DB")
# 紧耦合:UserService 内部创建 Database
class UserService:
def __init__(self):
self.db = Database() # ❌ 紧耦合
# 松耦合:从外部注入依赖
class UserService:
def __init__(self, db): # ✅ 依赖注入
self.db = db
2. 抽象接口
from abc import ABC, abstractmethod
class DatabaseInterface(ABC):
@abstractmethod
def connect(self):
pass
class MySQLDatabase(DatabaseInterface):
def connect(self):
print("Connecting to MySQL")
class UserService:
def __init__(self, db: DatabaseInterface): # 面向接口编程
self.db = db
3. 事件驱动架构
class EventBus:
def __init__(self):
self.listeners = []
def subscribe(self, listener):
self.listeners.append(listener)
def publish(self, event):
for listener in self.listeners:
listener(event)
45. Python中有哪些常用的设计模式?
创建型模式
单例模式:确保一个类只有一个实例。
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
ifnotcls._instance:
cls._instance = super().__new__(cls)
returncls._instance
工厂方法模式:将对象创建延迟到子类。
class CarFactory:
def create_car(self, car_type):
if car_type == "sedan":
return Sedan()
elif car_type == "truck":
return Truck()
结构型模式
适配器模式:将一个类的接口转换为客户期望的另一个接口。
装饰器模式:动态地给对象添加职责(Python的 @decorator 语法本质就是装饰器模式)。
代理模式:为对象提供代理以控制访问(如延迟加载、访问控制)。
行为型模式
观察者模式:一对多依赖,状态变化时通知所有依赖者。
策略模式:定义一系列算法,使它们可以相互替换。
class CarStrategy:
def travel(self): pass
class TrainStrategy:
def travel(self): return "Traveling by train"
context = TravelContext(TrainStrategy())
context.travel() # Traveling by train
46. Python的自省特性
自省(Introspection)是指程序在运行时检查对象类型、属性、方法等的能力。
# type():获取对象类型
print(type(42)) # <class 'int'>
# dir():列出对象的所有属性和方法
print(dir([1, 2, 3]))
# hasattr/getattr/setattr:动态操作属性
class Person:
name = "Alice"
p = Person()
print(hasattr(p, 'name')) # True
print(getattr(p, 'name')) # Alice
setattr(p, 'age', 30)
# isinstance/issubclass:检查继承关系
print(isinstance([], list)) # True
print(issubclass(bool, int)) # True(bool是int的子类)
# __dict__:查看对象的属性字典
print(p.__dict__) # {'age': 30}
# callable:检查是否可调用
print(callable(print)) # True
算法岗校招面试系列目前规划10+ 章 50+ 篇内容,涵盖 Python、C/C++、计网、数据结构、数字图像、机器学习、深度学习、大模型、Agent、算法题等所有算法岗面试核心模块。关注本号,第一时间收到更新。
#人工智能就业 #大模型 #校招面试 #算法面试 #Python