Python 知识点总结 - 进阶篇


五、内存管理

5.1 引用与引用计数

  • 引用:Python 中变量本质是对内存对象的引用(指针),而非存储数据本身。
  • 引用计数:每个对象维护一个计数器,记录被引用的次数。
  • 计数变化
    • 对象被赋值给变量:计数 +1。
    • 变量被删除(del)或重新赋值:计数 -1。
    • 计数为 0 时,对象被立即释放。
  • 示例
    a = [1, 2, 3]  # 列表对象引用计数 = 1
    b = a          # 引用计数 = 2
    c = a          # 引用计数 = 3
    
    del a          # 引用计数 = 2
    b = 10         # 引用计数 = 1
    c = None       # 引用计数 = 0,列表对象被释放
    

5.2 深浅拷贝

  • 浅拷贝
    • 仅拷贝表层数据,内层可变对象仍共享引用。
    • 方法:
      • 切片:new_list = old_list[:]
      • 工厂函数:new_list = list(old_list)
      • copy.copy()import copy; new_list = copy.copy(old_list)
  • 深拷贝
    • 递归拷贝所有层级的数据,新对象完全独立。
    • 方法:copy.deepcopy()
  • 示例
    import copy
    
    # 浅拷贝示例
    old_list = [1, [2, 3], 4]
    new_shallow = copy.copy(old_list)
    
    old_list[1].append(5)  # 修改内层列表
    print(old_list)        # [1, [2, 3, 5], 4]
    print(new_shallow)     # [1, [2, 3, 5], 4]  # 受影响
    
    # 深拷贝示例
    old_list = [1, [2, 3], 4]
    new_deep = copy.deepcopy(old_list)
    
    old_list[1].append(5)
    print(old_list)        # [1, [2, 3, 5], 4]
    print(new_deep)        # [1, [2, 3], 4]  # 不受影响
    

5.3 垃圾回收

  • 引用计数:实时回收机制,引用计数为 0 立即释放内存。
  • 分代垃圾回收
    • 问题:循环引用(如 a.append(b); b.append(a))会导致引用计数永远不为 0。
    • 解决方案:定期扫描对象图,检测不可达对象并回收。
  • 分代策略
    • 0代:新创建的对象,回收最频繁。
    • 1代:存活过一次回收的对象,中等频率回收。
    • 2代:长寿对象,回收频率最低。
  • 触发时机
    • 内存占用超过阈值。
    • 分配/释放次数达到阈值。
    • 手动调用 gc.collect()
  • 示例
    import gc
    
    # 手动触发垃圾回收
    gc.collect()
    
    # 查看垃圾回收统计信息
    print(gc.get_stats())
    
    # 设置垃圾回收阈值
    gc.set_threshold(700, 10, 10)
    

六、文件操作

6.1 文件打开与关闭

  • 打开文件open(file, mode, encoding)
    • file:文件路径(相对或绝对)。
    • mode:打开模式。
    • encoding:编码格式(如 utf-8)。
  • 关闭文件file.close(),释放系统资源。
  • 示例
    # 打开文件
    f = open("example.txt", "r", encoding="utf-8")
    
    # 读取内容
    content = f.read()
    print(content)
    
    # 关闭文件
    f.close()
    

6.2 打开模式

模式 说明
r 只读模式(默认),文件不存在报错
w 写入模式,覆盖原有内容,文件不存在则创建
a 追加模式,在文件末尾添加内容
b 二进制模式,用于处理图片、视频等二进制文件
+ 读写模式,与其他模式组合使用(如 r+w+

6.3 文件读写

  • 读取操作
    # 读取全部内容
    with open("example.txt", "r") as f:
        content = f.read()
    
    # 读取一行
    with open("example.txt", "r") as f:
        line = f.readline()
    
    # 读取所有行到列表
    with open("example.txt", "r") as f:
        lines = f.readlines()
    
  • 写入操作
    # 写入字符串
    with open("output.txt", "w") as f:
        f.write("Hello, World!\n")
    
    # 写入多行
    lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
    with open("output.txt", "w") as f:
        f.writelines(lines)
    

6.4 上下文管理器

  • 语法with open(...) as 变量名:
  • 特点
    • 自动管理资源,代码块执行完毕后自动关闭文件。
    • 即使发生异常也能正确关闭文件。
  • 多文件操作
    with open("input.txt", "r") as f_in, open("output.txt", "w") as f_out:
        content = f_in.read()
        f_out.write(content)
    

七、模块与包

7.1 模块

  • 定义:一个 .py 文件即为一个模块,包含变量、函数、类等。
  • 作用
    • 代码复用:将常用功能封装为模块,供其他程序调用。
    • 命名空间管理:避免变量名冲突。
  • 导入方式
    # 导入整个模块
    import math
    print(math.pi)  # 3.14159...
    
    # 导入并指定别名
    import numpy as np
    arr = np.array([1, 2, 3])
    
    # 导入指定成员
    from math import sqrt, pi
    print(sqrt(16))  # 4.0
    
    # 导入所有成员(不推荐)
    from math import *
    

7.2 包

  • 定义:包含 __init__.py 文件的目录,用于组织多个相关模块。
  • __init__.py:初始化文件,可为空,也可包含包的初始化代码。
  • 示例结构
    my_package/
        __init__.py
        module1.py
        module2.py
        sub_package/
            __init__.py
            module3.py
    
  • 导入方式
    import my_package.module1
    from my_package import module2
    from my_package.sub_package import module3
    

7.3 标准库模块

  • os:操作系统接口,处理文件和目录。
    import os
    
    # 获取当前目录
    print(os.getcwd())
    
    # 创建目录
    os.makedirs("new_folder", exist_ok=True)
    
    # 遍历目录
    for item in os.listdir("."):
        print(item)
    
  • sys:系统相关功能,如命令行参数、标准输入输出。
    import sys
    
    # 命令行参数
    print(sys.argv)
    
    # 退出程序
    sys.exit(0)
    
  • math:数学函数。
  • random:随机数生成。
    import random
    
    # 随机整数
    print(random.randint(1, 10))
    
    # 随机选择
    print(random.choice(["a", "b", "c"]))
    
  • datetime:日期时间处理。
    from datetime import datetime, timedelta
    
    # 当前时间
    now = datetime.now()
    print(now)
    
    # 时间运算
    tomorrow = now + timedelta(days=1)
    print(tomorrow)
    
  • json:JSON 数据处理。
  • re:正则表达式。

八、面向对象

8.1 类定义

  • 语法
    class Person:
        """人类"""
        
        # 类属性
        species = "Homo sapiens"
        
        def __init__(self, name, age):
            """构造方法,初始化对象"""
            self.name = name  # 实例属性
            self.age = age
        
        def greet(self):
            """实例方法"""
            print(f"Hello, my name is {self.name}")
        
        @classmethod
        def get_species(cls):
            """类方法"""
            return cls.species
        
        @staticmethod
        def is_adult(age):
            """静态方法"""
            return age >= 18
    
    # 实例化
    person = Person("Alice", 25)
    person.greet()  # Hello, my name is Alice
    
  • 构造方法__init__,创建对象时自动调用。
  • 实例化obj = 类名(参数)
  • self:代表实例本身,在方法中访问实例属性和方法。

8.2 继承

  • 语法
    class Animal:
        def __init__(self, name):
            self.name = name
        
        def speak(self):
            print("Animal speaks")
    
    class Dog(Animal):
        def __init__(self, name, breed):
            super().__init__(name)  # 调用父类构造方法
            self.breed = breed
        
        def speak(self):
            print(f"{self.name} says Woof!")  # 重写父类方法
    
    dog = Dog("Buddy", "Golden Retriever")
    dog.speak()  # Buddy says Woof!
    
  • 作用:子类继承父类的属性和方法,实现代码复用。
  • 方法重写:子类可以覆盖父类的方法。

8.3 封装、继承、多态

  • 封装:将数据(属性)和操作(方法)封装在类内部,隐藏实现细节。
    • 通过访问控制(如 _private 约定私有属性)保护数据。
    class Person:
        def __init__(self, name, age):
            self.name = name    # 公开属性
            self._age = age     # 约定私有属性(单下划线)
            self.__secret = "secret"  # 真正私有(双下划线)
        
        def get_age(self):
            return self._age
    
  • 继承:子类获得父类的属性和方法,支持层次化设计。
  • 多态:同一接口有多种实现方式,提高代码灵活性。
    class Cat(Animal):
        def speak(self):
            print("Meow!")
    
    def make_speak(animal):
        animal.speak()
    
    dog = Dog("Buddy", "Labrador")
    cat = Cat("Whiskers")
    
    make_speak(dog)  # Buddy says Woof!
    make_speak(cat)  # Meow!
    

九、异常处理

9.1 基本语法

  • try-except
    try:
        num = int(input("Enter a number: "))
        result = 10 / num
    except ValueError:
        print("Please enter a valid number")
    except ZeroDivisionError:
        print("Cannot divide by zero")
    
  • try-except-else
    try:
        num = int(input("Enter a number: "))
        result = 10 / num
    except ValueError:
        print("Invalid input")
    else:
        print(f"Result: {result}")  # 无异常时执行
    
  • try-except-finally
    try:
        f = open("file.txt", "r")
        content = f.read()
    except FileNotFoundError:
        print("File not found")
    finally:
        if 'f' in locals():
            f.close()  # 无论是否异常都执行
    

9.2 常见异常

异常类型 说明 示例
ValueError 值错误 int("abc")
TypeError 类型错误 1 + "2"
FileNotFoundError 文件不存在 open("nonexistent.txt")
IndexError 索引越界 list[10] 当列表只有5个元素
KeyError 字典键不存在 dict["nonexistent"]
ZeroDivisionError 除零错误 10 / 0
AttributeError 属性不存在 str.nonexistent_method()

9.3 自定义异常

  • 语法:继承 Exception
    class InvalidAgeError(Exception):
        """自定义异常:无效年龄"""
        def __init__(self, age):
            self.age = age
            super().__init__(f"Invalid age: {age}. Age must be positive.")
    
    # 使用自定义异常
    def check_age(age):
        if age < 0:
            raise InvalidAgeError(age)
        print(f"Age {age} is valid")
    
    try:
        check_age(-5)
    except InvalidAgeError as e:
        print(e)  # Invalid age: -5. Age must be positive.
    

十、JSON 处理

10.1 JSON 简介

  • JSON(JavaScript Object Notation):轻量级数据交换格式。
  • 结构:键值对(类似 Python 字典)、数组(类似 Python 列表)。
  • Python 支持:标准库 json 模块提供 JSON 序列化和反序列化功能。

10.2 常用方法

  • json.dumps():将 Python 对象序列化为 JSON 字符串
    import json
    
    data = {
        "name": "Alice",
        "age": 25,
        "is_student": True,
        "hobbies": ["reading", "coding"]
    }
    
    json_str = json.dumps(data)
    print(json_str)
    # {"name": "Alice", "age": 25, "is_student": true, "hobbies": ["reading", "coding"]}
    
  • json.loads():将 JSON 字符串反序列化为 Python 对象
    json_str = '{"name": "Alice", "age": 25}'
    data = json.loads(json_str)
    print(data["name"])  # Alice
    
  • json.dump():将 Python 对象写入 JSON 文件
    with open("data.json", "w") as f:
        json.dump(data, f)
    
  • json.load():从 JSON 文件读取数据
    with open("data.json", "r") as f:
        data = json.load(f)
    

十一、函数式编程

11.1 函数式编程概念

  • 核心思想:将计算视为函数应用,避免状态变化和可变数据。
  • 特点
    • 纯函数:相同输入始终产生相同输出,无副作用。
    • 高阶函数:接受函数作为参数或返回函数。
    • 不可变数据:数据一旦创建不可修改。

11.2 map 函数

  • 作用:将函数应用于可迭代对象的每个元素,返回迭代器。
  • 语法map(function, iterable)
  • 示例
    numbers = [1, 2, 3, 4]
    
    # 使用 lambda 函数
    squared = map(lambda x: x ** 2, numbers)
    print(list(squared))  # [1, 4, 9, 16]
    
    # 使用普通函数
    def double(x):
        return x * 2
    
    doubled = map(double, numbers)
    print(list(doubled))  # [2, 4, 6, 8]
    

11.3 filter 函数

  • 作用:根据条件过滤可迭代对象的元素,返回迭代器。
  • 语法filter(function, iterable)
  • 示例
    numbers = [1, 2, 3, 4, 5, 6]
    
    # 过滤偶数
    even_numbers = filter(lambda x: x % 2 == 0, numbers)
    print(list(even_numbers))  # [2, 4, 6]
    
    # 过滤大于 3 的数
    greater_than_3 = filter(lambda x: x > 3, numbers)
    print(list(greater_than_3))  # [4, 5, 6]
    

11.4 reduce 函数

  • 作用:将函数累积应用于可迭代对象的元素,返回单个值。
  • 语法reduce(function, iterable[, initial])
  • 注意:Python 3 中需从 functools 导入。
  • 示例
    from functools import reduce
    
    numbers = [1, 2, 3, 4]
    
    # 计算乘积
    product = reduce(lambda x, y: x * y, numbers)
    print(product)  # 24
    
    # 计算累加和(带初始值)
    total = reduce(lambda x, y: x + y, numbers, 10)
    print(total)  # 20(10 + 1 + 2 + 3 + 4)
    

十二、并发编程

12.1 并行、串行、并发

  • 串行:任务按顺序执行,一个完成后再执行下一个。
    # 串行执行
    def task1():
        print("Task 1")
    
    def task2():
        print("Task 2")
    
    task1()
    task2()  # 等待 task1 完成后执行
    
  • 并行:多个任务同时执行(需要多核 CPU)。
  • 并发:多个任务交替执行,宏观上同时进行。

12.2 进程、线程、协程

  • 进程:操作系统分配资源的基本单位,每个进程有独立内存空间。
  • 线程:进程内的执行单元,共享进程内存空间。
  • 协程:轻量级线程,由用户程序控制调度,开销极小。

12.3 同步和异步

  • 同步:任务按顺序执行,调用方等待结果返回。
  • 异步:任务提交后立即返回,结果通过回调或 Future 获取。
  • 异步 IO:非阻塞 IO 操作,提高程序吞吐量。

12.4 常用并发模块

  • threading:多线程编程。
    import threading
    
    def print_numbers():
        for i in range(5):
            print(f"Thread 1: {i}")
    
    def print_letters():
        for letter in ['a', 'b', 'c', 'd', 'e']:
            print(f"Thread 2: {letter}")
    
    t1 = threading.Thread(target=print_numbers)
    t2 = threading.Thread(target=print_letters)
    
    t1.start()
    t2.start()
    
    t1.join()
    t2.join()
    
  • multiprocessing:多进程编程。
    from multiprocessing import Process
    
    def worker(name):
        print(f"Worker {name} started")
    
    if __name__ == "__main__":
        p1 = Process(target=worker, args=("A",))
        p2 = Process(target=worker, args=("B",))
        
        p1.start()
        p2.start()
        
        p1.join()
        p2.join()
    
  • asyncio:异步 IO 编程(Python 3.5+)。
    import asyncio
    
    async def say_hello():
        print("Hello")
        await asyncio.sleep(1)
        print("World")
    
    async def main():
        await asyncio.gather(say_hello(), say_hello())
    
    asyncio.run(main())
    
  • concurrent.futures:高级并发接口,支持线程池和进程池。
    from concurrent.futures import ThreadPoolExecutor
    
    def square(x):
        return x ** 2
    
    with ThreadPoolExecutor(max_workers=3) as executor:
        results = executor.map(square, [1, 2, 3, 4, 5])
        print(list(results))  # [1, 4, 9, 16, 25]
    

更多推荐