当前位置:首页>python>Python从入门到精通day31

Python从入门到精通day31

  • 2026-02-11 12:31:41
Python从入门到精通day31

Python语言进阶

Python 进阶的核心,是跳出 “能用就行” 的基础编程思维,掌握更高效的语法、更合理的数据结构、更优的算法思路、更工程化的编程范式(函数式 / 面向对象 / 并发),最终写出性能更高、可读性更好、可维护性更强的代码。

本文将从高效语法、内置工具模块、算法基础、函数进阶、面向对象进阶、迭代器 / 生成器、并发编程七大维度,系统梳理 Python 进阶的核心知识点,结合实战案例拆解难点,帮你从 “会写代码” 升级为 “会写好代码”。

一、高效语法:生成式与嵌套列表陷阱

  • 1.生成式(推导式):极简构建容器
  • 生成式是 Python 特有的高效语法,可一键生成列表、集合、字典,替代繁琐的for循环 +append,代码更简洁、执行效率更高。
prices = {'AAPL'191.88,'GOOG'1186.96,'IBM'149.24,'ORCL'48.44,'ACN'166.89,'FB'208.09,'SYMC'21.29}# 用股票价格大于100元的股票构造一个新的字典prices2 = {key: value for key, value in prices.items() if value > 100}print(prices2)

说明:生成式是 Python 特有的高效语法,可一键生成列表、集合、字典,替代繁琐的for循环 +append,代码更简洁、执行效率更高。

  • 2.嵌套列表的坑:浅拷贝问题
  • 新手常因嵌套列表的浅拷贝导致数据错乱,核心原因是:[list] * n 会让所有元素指向同一个列表对象
names = ['关羽''张飞''赵云''马超''黄忠']courses = ['语文''数学''英语']# 录入五个学生三门课程的成绩# 错误 - 参考http://pythontutor.com/visualize.html#mode=edit# scores = [[None] * len(courses)] * len(names)scores = [[None] * len(courses) for _ inrange(len(names))]for row, name inenumerate(names):for col, course inenumerate(courses):        scores[row][col] = float(input(f'请输入{name}{course}成绩: '))print(scores)
Python Tutor - VISUALIZE CODE AND GET LIVE HELP

二、Python 内置高效模块:避免重复造轮子

Python 标准库提供了大量优化过的工具模块,无需手写复杂逻辑,直接调用即可提升性能。
  • heapq:堆排序找极值
  • heapq块基于堆结构实现,可高效找出列表中最大 / 最小的 N 个元素(时间复杂度 O (n log k),优于排序后切片的 O (n log n))。
    """从列表中找出最大的或最小的N个元素堆结构(大根堆/小根堆)"""import heapqlist1 = [34251299876358788892]list2 = [    {'name''IBM''shares'100'price'91.1},    {'name''AAPL''shares'50'price'543.22},    {'name''FB''shares'200'price'21.09},    {'name''HPQ''shares'35'price'31.75},    {'name''YHOO''shares'45'price'16.35},    {'name''ACME''shares'75'price'115.65}]print(heapq.nlargest(3, list1))print(heapq.nsmallest(3, list1))print(heapq.nlargest(2, list2, key=lambda x: x['price']))print(heapq.nlargest(2, list2, key=lambda x: x['shares']))
  • • itertools:迭代器工具集
    itertools提供了高效的迭代器生成函数,支持排列、组合、笛卡尔积等场景,节省内存(迭代器按需生成元素,不一次性加载)。
  • """迭代工具模块"""import itertools# 产生ABCD的全排列itertools.permutations('ABCD')# 产生ABCDE的五选三组合itertools.combinations('ABCDE'3)# 产生ABCD和123的笛卡尔积itertools.product('ABCD''123')# 产生ABC的无限循环序列itertools.cycle(('A''B''C'))
  • • collections:增强版集合类型
  • collections是 Python 内置的 “数据结构增强包”,解决原生列表 / 字典的不足,常用工具类如下:
  • 工具类
    功能
    实战示例
    Counter
    计数(统计元素出现次数)
    Counter(words).most_common(3)
    namedtuple
    命名元组(替代类的轻量方案)
    Point = namedtuple('Point', ['x','y'])
    deque
    双端队列(头尾增删 O (1),列表是 O (n))
    dq.appendleft(1)
    /dq.popright()
    defaultdict
    带默认值的字典(避免 KeyError)
    dd = defaultdict(list)
    OrderedDict
    有序字典(Python3.7 + 字典已有序,仍有用)
    记录插入顺序
    实战示例:统计高频单词
    """找出序列中出现次数最多的元素"""from collections import Counterwords = ['look''into''my''eyes''look''into''my''eyes','the''eyes''the''eyes''the''eyes''not''around','the''eyes'"don't"'look''around''the''eyes','look''into''my''eyes'"you're"'under']counter = Counter(words)print(counter.most_common(3))

    三 、数据结构和算法

    • 算法是解决问题的核心,Python 进阶需掌握算法复杂度分析经典算法思想

      1. 算法复杂度:大 O 标记

      算法的好坏用时间复杂度(执行步骤)和空间复杂度(占用内存)衡量,常用大 O 标记表示 “渐近复杂度”:

    • 复杂度
      标记
      典型算法
      特点
      常量时间
      O(1)
      哈希查找、布隆过滤器
      执行时间与数据量无关
      对数时间
      O(logn)
      二分查找
      数据量翻倍,步骤 + 1
      线性时间
      O(n)
      顺序查找、计数排序
      步骤与数据量成正比
      对数线性
      O(nlogn)
      归并 / 快速排序
      高效排序算法
      平方时间
      O(n²)
      冒泡 / 选择 / 插入排序
      数据量翻倍,步骤 ×4
      阶乘时间
      O(n!)
      旅行商问题(穷举)
      数据量稍大就无法执行

      2. 经典排序 / 查找算法

    • (1)排序算法

    • 算法
      实现思路
      时间复杂度(平均)
      稳定性
      选择排序
      选最小元素放到已排序区
      O(n²)
      不稳定
      冒泡排序
      相邻元素交换,大元素 “冒泡” 到末尾
      O(n²)
      稳定
      归并排序
      分治:拆分子列表→排序→合并
      O(nlogn)
      稳定
      快速排序
      分治:选枢轴→分区→递归排序
      O(nlogn)
      不稳定
    归并排序核心实现
      • defmerge_sort(items):"""归并排序(分治思想)"""iflen(items) < 2:return items    mid = len(items) // 2    left = merge_sort(items[:mid])    right = merge_sort(items[mid:])# 合并两个有序子列表    result = []    i = j = 0while i < len(left) and j < len(right):if left[i] < right[j]:            result.append(left[i])            i += 1else:            result.append(right[j])            j += 1    result += left[i:] + right[j:]return result# 测试print(merge_sort([3425129987]))  # [12, 25, 34, 87, 99]
      (2)查找算法
      算法
      实现思路
      时间复杂度
      适用场景
      顺序查找
      遍历列表逐个比对
      O(n)
      无序列表
      二分查找
      有序列表中折半缩小范围
      O(logn)
      有序列表(不可频繁增删)
      3. 经典算法思想
      • 思想
        核心逻辑
        实战示例
        穷举法
        遍历所有可能,验证是否符合条件
        百钱百鸡、五人分鱼
        贪婪法
        每步选局部最优,不追求全局最优
        背包问题(快速找满意解)
        分治法
        拆分子问题→解决→合并结果
        快速排序、归并排序
        回溯法
        试探→失败则回退重新选择
        骑士巡逻、八皇后
        动态规划
        缓存子问题解,避免重复计算
        最大子数组和
      • 动态规划实战:最大子数组和

      说明:子列表指的是列表中索引(下标)连续的元素构成的列表;列表中的元素是int类型,可能包含正整数、0、负整数;程序输入列表中的元素,输出子列表元素求和的最大值,例如:

      输入:1 -2 3 5 -3 2

      输出:8

      输入:0 -2 3 5 -1 2

      输出:9

      输入:-9 -2 -3 -5 -3

      输出:-2

      defmain():    items = list(map(intinput().split()))    overall = partial = items[0]for i inrange(1len(items)):        partial = max(items[i], partial + items[i])        overall = max(partial, overall)print(overall)if __name__ == '__main__':    main()

      说明:这个题目最容易想到的解法是使用二重循环,但是代码的时间性能将会变得非常的糟糕。使用动态规划的思想,仅仅是多用了两个变量,就将原来复杂度的问题变成了

        • • 穷举法 - 又称为暴力破解法,对所有的可能性进行验证,直到找到正确答案。
        • • 贪婪法 - 在对问题求解时,总是做出在当前看来
        • • 最好的选择,不追求最优解,快速找到满意解。
        • • 分治法 - 把一个复杂的问题分成两个或更多的相同或相似的子问题,再把子问题分成更小的子问题,直到可以直接求解的程度,最后将子问题的解进行合并得到原问题的解。
        • • 回溯法 - 回溯法又称为试探法,按选优条件向前搜索,当搜索到某一步发现原先选择并不优或达不到目标时,就退回一步重新选择。
        • • 动态规划 - 基本思想也是将待求解问题分解成若干个子问题,先求解并保存这些子问题的解,避免产生大量的重复运算。

      四、函数的使用方式

      • Python 中函数是 “一等公民”(可赋值、传参、返回),基于此可实现高阶函数、闭包、装饰器等进阶用法。
      • 1. 核心特性
      • 函数赋值:func = lambda x: x²
      • 函数传参:map(func, iterable)
      • 函数返回:装饰器返回包装后的函数
      • 高阶函数:filter/map(推荐用生成式替代,更易读):
      • items1 = list(map(lambda x: x ** 2filter(lambda x: x % 2range(110))))items2 = [x ** 2for x inrange(110if x % 2]
      • • 位置参数、可变参数、关键字参数、命名关键字参数
      • • 参数的元信息(代码可读性问题)
      • • 匿名函数和内联函数的用法(lambda函数)
      • 2.闭包和作用域问题
      • LEGB 规则:Python 查找变量顺序→Local(局部)→Embedded(嵌套)→Global(全局)→Built-in(内置)
      • global:声明 / 定义全局变量
      • nonlocal:声明使用嵌套作用域变量(必须已存在)
      3.装饰器函数
      装饰器是闭包的典型应用,用于无侵入增强函数功能(如计时、日志、单例)。
      (1)基础装饰器(记录函数执行时间)
      defrecord_time(func):"""自定义装饰函数的装饰器"""    @wraps(func)defwrapper(*args, **kwargs):        start = time()        result = func(*args, **kwargs)print(f'{func.__name__}{time() - start}秒')return resultreturn wrapper
      (2)参数化装饰器(可自定义输出方式)
      from functools import wrapsfrom time import timedefrecord(output):"""可以参数化的装饰器"""defdecorate(func):        @wraps(func)defwrapper(*args, **kwargs):            start = time()            result = func(*args, **kwargs)            output(func.__name__, time() - start)return resultreturn wrapperreturn decorate
      from functools import wrapsfrom time import timeclassRecord():"""通过定义类的方式定义装饰器"""def__init__(self, output):self.output = outputdef__call__(self, func):        @wraps(func)defwrapper(*args, **kwargs):            start = time()            result = func(*args, **kwargs)self.output(func.__name__, time() - start)return resultreturn wrapper

      说明:由于对带装饰功能的函数添加了@wraps装饰器,可以通过func.__wrapped__方式获得被装饰之前的函数或类来取消装饰器的作用。

      例子:用装饰器来实现单例模式。
      from functools import wrapsdefsingleton(cls):"""装饰类的装饰器"""    instances = {}    @wraps(cls)defwrapper(*args, **kwargs):if cls notin instances:            instances[cls] = cls(*args, **kwargs)return instances[cls]return wrapper@singletonclassPresident:"""总统(单例类)"""pass

      提示:上面的代码中用到了闭包(closure),不知道你是否已经意识到了。还没有一个小问题就是,上面的代码并没有实现线程安全的单例,如果要实现线程安全的单例应该怎么做呢?

      from functools import wrapsfrom threading import RLockdefsingleton(cls):"""线程安全的单例装饰器"""    instances = {}    locker = RLock()    @wraps(cls)defwrapper(*args, **kwargs):if cls notin instances:with locker:if cls notin instances:                    instances[cls] = cls(*args, **kwargs)return instances[cls]return wrapper

      提示:上面的代码用到了with上下文语法来进行锁操作,因为锁对象本身就是上下文管理器对象(支持__enter____exit__魔术方法)。在wrapper函数中,我们先做了一次不带锁的检查,然后再做带锁的检查,这样做比直接加锁检查性能要更好,如果对象已经创建就没有必须再去加锁而是直接返回该对象就可以了。

      五、面向对象相关知识

      面向对象(OOP)是工程化编程的核心,Python 进阶需掌握 OOP 三大支柱、类间关系、元编程等。
      • 1.三大支柱实战:工资结算系统
        """月薪结算系统 - 部门经理每月15000 程序员每小时200 销售员1800底薪加销售额5%提成"""from abc import ABCMeta, abstractmethodclassEmployee(metaclass=ABCMeta):"""员工(抽象类)"""def__init__(self, name):self.name = name    @abstractmethoddefget_salary(self):"""结算月薪(抽象方法)"""passclassManager(Employee):"""部门经理"""defget_salary(self):return15000.0classProgrammer(Employee):"""程序员"""def__init__(self, name, working_hour=0):self.working_hour = working_hoursuper().__init__(name)defget_salary(self):return200.0 * self.working_hourclassSalesman(Employee):"""销售员"""def__init__(self, name, sales=0.0):self.sales = salessuper().__init__(name)defget_salary(self):return1800.0 + self.sales * 0.05classEmployeeFactory:"""创建员工的工厂(工厂模式 - 通过工厂实现对象使用者和对象之间的解耦合)"""    @staticmethoddefcreate(emp_type, *args, **kwargs):"""创建员工"""        all_emp_types = {'M': Manager, 'P': Programmer, 'S': Salesman}        cls = all_emp_types[emp_type.upper()]return cls(*args, **kwargs) if cls elseNonedefmain():"""主函数"""    emps = [        EmployeeFactory.create('M''曹操'),         EmployeeFactory.create('P''荀彧'120),        EmployeeFactory.create('P''郭嘉'85),         EmployeeFactory.create('S''典韦'123000),    ]for emp in emps:print(f'{emp.name}{emp.get_salary():.2f}元')if __name__ == '__main__':    main()
      • 2.类间关系

        例子:扑克游戏。

        """经验:符号常量总是优于字面常量,枚举类型是定义符号常量的最佳选择"""from enum import Enum, uniqueimport random@uniqueclassSuite(Enum):"""花色"""    SPADE, HEART, CLUB, DIAMOND = range(4)def__lt__(self, other):returnself.value < other.valueclassCard:"""牌"""def__init__(self, suite, face):"""初始化方法"""self.suite = suiteself.face = facedefshow(self):"""显示牌面"""        suites = ['♠︎''♥︎''♣︎''♦︎']        faces = ['''A''2''3''4''5''6''7''8''9''10''J''Q''K']returnf'{suites[self.suite.value]}{faces[self.face]}'def__repr__(self):returnself.show()classPoker:"""扑克"""def__init__(self):self.index = 0self.cards = [Card(suite, face)for suite in Suitefor face inrange(114)]defshuffle(self):"""洗牌(随机乱序)"""        random.shuffle(self.cards)self.index = 0defdeal(self):"""发牌"""        card = self.cards[self.index]self.index += 1return card    @propertydefhas_more(self):returnself.index < len(self.cards)classPlayer:"""玩家"""def__init__(self, name):self.name = nameself.cards = []defget_one(self, card):"""摸一张牌"""self.cards.append(card)defsort(self, comp=lambda card: (card.suite, card.face)):"""整理手上的牌"""self.cards.sort(key=comp)defmain():"""主函数"""    poker = Poker()    poker.shuffle()    players = [Player('东邪'), Player('西毒'), Player('南帝'), Player('北丐')]while poker.has_more:for player in players:                player.get_one(poker.deal())for player in players:        player.sort()print(player.name, end=': ')print(player.cards)if __name__ == '__main__':    main()

        说明:上面的代码中使用了Emoji字符来表示扑克牌的四种花色,在某些不支持Emoji字符的系统上可能无法显示。

        • • is-a关系:继承
        • • has-a关系:关联 / 聚合 / 合成
        • • use-a关系:依赖
      • • 对象的复制(深复制/深拷贝/深度克隆和浅复制/浅拷贝/影子克隆)
      • • 垃圾回收、循环引用和弱引用Python使用了自动化内存管理,这种管理机制以引用计数为基础,同时也引入了标记-清除分代收集两种机制为辅的策略。
        typedefstruct _object {/* 引用计数 */int ob_refcnt;/* 对象指针 */struct _typeobject *ob_type;} PyObject;
        /* 增加引用计数的宏定义 */#define Py_INCREF(op)   ((op)->ob_refcnt++)/* 减少引用计数的宏定义 */#define Py_DECREF(op) \ //减少计数if (--(op)->ob_refcnt != 0) \        ; \else \        __Py_Dealloc((PyObject *)(op))
        导致引用计数+1的情况:

        导致引用计数-1的情况:

        引用计数可能会导致循环引用问题,而循环引用会导致内存泄露,如下面的代码所示。为了解决这个问题,Python中引入了“标记-清除”和“分代收集”。在创建一个对象的时候,对象被放在第一代中,如果在第一代的垃圾检查中对象存活了下来,该对象就会被放到第二代中,同理在第二代的垃圾检查中对象存活下来,该对象就会被放到第三代中。

        # 循环引用会导致内存泄露 - Python除了引用技术还引入了标记清理和分代回收# 在Python 3.6以前如果重写__del__魔术方法会导致循环引用处理失效# 如果不想造成循环引用可以使用弱引用list1 = []list2 = [] list1.append(list2)list2.append(list1)

        以下情况会导致垃圾回收:

        如果循环引用中两个对象都定义了__del__方法,gc模块不会销毁这些不可达对象,因为gc模块不知道应该先调用哪个对象的__del__方法,这个问题在Python 3.6中得到了解决。

        也可以通过weakref模块构造弱引用的方式来解决循环引用的问题。

        • • 调用gc.collect()
        • • gc模块的计数器达到阀值
        • • 程序退出
        • • 对象的别名被显式销毁,例如del a
        • • 对象的别名被赋予新的对象,例如a = 24
        • • 一个对象离开它的作用域,例如f函数执行完毕时,f函数中的局部变量(全局变量不会)
        • • 对象所在的容器被销毁,或从容器中删除对象
        • • 对象被创建,例如a = 23
        • • 对象被引用,例如b = a
        • • 对象被作为参数,传入到一个函数中,例如f(a)
        • • 对象作为一个元素,存储在容器中,例如list1 = [a, a]
      • • 魔法属性和方法(请参考《Python魔法方法指南》)有几个小问题请大家思考:
        • • 自定义的对象能不能使用运算符做运算?
        • • 自定义的对象能不能放到set中?能去重吗?
        • • 自定义的对象能不能作为dict的键?
        • • 自定义的对象能不能使用上下文语法?
      • • 混入(Mixin)例子:自定义字典限制只有在指定的key不存在时才能在字典中设置键值对。
        classSetOnceMappingMixin:"""自定义混入类"""    __slots__ = ()def__setitem__(self, key, value):if key inself:raise KeyError(str(key) + ' already set')returnsuper().__setitem__(key, value)classSetOnceDict(SetOnceMappingMixin, dict):"""自定义字典"""passmy_dict= SetOnceDict()try:    my_dict['username'] = 'jackfrued'    my_dict['username'] = 'hellokitty'except KeyError:passprint(my_dict)
      • 3. 元编程与元类
      •     元编程和元类对象是通过类创建的,类是通过元类创建的,元类提供了创建类的元信息。所有的类都直接或间接的继承自object,所有的元类都直接或间接的继承自type。例子:用元类实现单例模式。
        import threadingclassSingletonMeta(type):"""自定义元类"""def__init__(cls, *args, **kwargs):        cls.__instance = None        cls.__lock = threading.RLock()super().__init__(*args, **kwargs)def__call__(cls, *args, **kwargs):if cls.__instance isNone:with cls.__lock:if cls.__instance isNone:                    cls.__instance = super().__call__(*args, **kwargs)return cls.__instanceclassPresident(metaclass=SingletonMeta):"""总统(单例类)"""pass
      4.面向对象设计原则(SOLID)
      • 单一职责(SRP):一个类只做一件事
      • 开闭原则(OCP):对扩展开放,对修改关闭
      • 依赖倒转(DIP):面向抽象编程
      • 里氏替换(LSP):子类可替换父类
      • 接口隔离(ISP):接口小而专,不贪
      • 合成聚合复用(CARP):优先组合,而非继承
      • 迪米特法则(LoD):最少知识,减少耦合

      六、迭代器和生成器

      迭代器和生成器是 Python 的 “内存友好型” 序列处理工具,按需生成元素,避免一次性加载所有数据。
      • 1. 迭代器:实现迭代器协议
      • 自定义迭代器需实现__iter____next__方法:
        classFib(object):"""迭代器"""def__init__(self, num):self.num = numself.a, self.b = 01self.idx = 0def__iter__(self):returnselfdef__next__(self):ifself.idx < self.num:self.a, self.b = self.b, self.a + self.bself.idx += 1returnself.araise StopIteration()
        • • Python中没有像protocolinterface这样的定义协议的关键字。
        • • Python中用魔术方法表示协议。
        • • __iter____next__魔术方法就是迭代器协议。
      2. 生成器:简化迭代器(yield 关键字)
      • • 生成器是语法简化版的迭代器。
        deffib(num):"""生成器"""    a, b = 01for _ inrange(num):        a, b = b, a + byield a
      • 3. 协程:生成器的进化(send () 方法)
      • • 生成器进化为协程。生成器对象可以使用send()方法发送数据,发送的数据会成为生成器函数中通过yield表达式获得的值。这样,生成器就可以作为协程使用,协程简单的说就是可以相互协作的子程序。
        defcalc_avg():"""流式计算平均值"""    total, counter = 00    avg_value = NonewhileTrue:        value = yield avg_value        total, counter = total + value, counter + 1        avg_value = total / countergen = calc_avg()next(gen)print(gen.send(10))print(gen.send(20))print(gen.send(30))

      七、并发编程

      Python 实现并发有三种方案,需根据场景选择,核心是解决 GIL(全局解释器锁)问题。

      1. 核心概念

      • 进程
        操作系统分配内存的基本单位(独立内存空间)
      • 线程
        操作系统分配 CPU 的基本单位(共享进程内存)
      • GIL
        CPython 的全局锁,导致多线程无法利用多核(仅 I/O 密集型场景有优势)
      • 2. 三种方案对比
      • 方案
        优势
        劣势
        适用场景
        多线程
        轻量、共享内存、切换成本低
        GIL 限制,无法多核并行
        I/O 密集型(文件 / 网络操作)
        多进程
        利用多核,无 GIL 限制
        内存隔离、切换成本高
        计算密集型(数学运算 / 排序)
        异步 I/O
        单线程并发,资源消耗极低
        编程模型复杂,依赖异步库
        高并发 I/O(Web 服务器)
        3.实战示例
      • 1)多线程:线程安全的银行账户
      • • 多线程:Python中提供了Thread类并辅以LockConditionEventSemaphoreBarrier。Python中有GIL来防止多个线程同时执行本地字节码,这个锁对于CPython是必须的,因为CPython的内存管理并不是线程安全的,因为GIL的存在多线程并不能发挥CPU的多核特性。
        """面试题:进程和线程的区别和联系?进程 - 操作系统分配内存的基本单位 - 一个进程可以包含一个或多个线程线程 - 操作系统分配CPU的基本单位并发编程(concurrent programming)1. 提升执行性能 - 让程序中没有因果关系的部分可以并发的执行2. 改善用户体验 - 让耗时间的操作不会造成程序的假死"""import globimport osimport threadingfrom PIL import ImagePREFIX = 'thumbnails'defgenerate_thumbnail(infile, size, format='PNG'):"""生成指定图片文件的缩略图"""    file, ext = os.path.splitext(infile)    file = file[file.rfind('/') + 1:]    outfile = f'{PREFIX}/{file}_{size[0]}_{size[1]}.{ext}'    img = Image.open(infile)    img.thumbnail(size, Image.ANTIALIAS)    img.save(outfile, format)defmain():"""主函数"""ifnot os.path.exists(PREFIX):        os.mkdir(PREFIX)for infile in glob.glob('images/*.png'):for size in (3264128):# 创建并启动线程            threading.Thread(                target=generate_thumbnail,                 args=(infile, (size, size))            ).start()if __name__ == '__main__':    main()
        多个线程竞争资源的情况。
        """多线程程序如果没有竞争资源处理起来通常也比较简单当多个线程竞争临界资源的时候如果缺乏必要的保护措施就会导致数据错乱说明:临界资源就是被多个线程竞争的资源"""import timeimport threadingfrom concurrent.futures import ThreadPoolExecutorclassAccount(object):"""银行账户"""def__init__(self):self.balance = 0.0self.lock = threading.Lock()defdeposit(self, money):# 通过锁保护临界资源withself.lock:            new_balance = self.balance + money            time.sleep(0.001)self.balance = new_balancedefmain():"""主函数"""    account = Account()# 创建线程池    pool = ThreadPoolExecutor(max_workers=10)    futures = []for _ inrange(100):        future = pool.submit(account.deposit, 1)        futures.append(future)# 关闭线程池    pool.shutdown()for future in futures:        future.result()print(account.balance)if __name__ == '__main__':    main()
        修改上面的程序,启动5个线程向账户中存钱,5个线程从账户中取钱,取钱时如果余额不足就暂停线程进行等待。为了达到上述目标,需要对存钱和取钱的线程进行调度,在余额不足时取钱的线程暂停并释放锁,而存钱的线程将钱存入后要通知取钱的线程,使其从暂停状态被唤醒。可以使用threading模块的Condition来实现线程调度,该对象也是基于锁来创建的,代码如下所示:
        """多个线程竞争一个资源 - 保护临界资源 - 锁(Lock/RLock)多个线程竞争多个资源(线程数>资源数) - 信号量(Semaphore)多个线程的调度 - 暂停线程执行/唤醒等待中的线程 - Condition"""from concurrent.futures import ThreadPoolExecutorfrom random import randintfrom time import sleepimport threadingclassAccount:"""银行账户"""def__init__(self, balance=0):self.balance = balance        lock = threading.RLock()self.condition = threading.Condition(lock)defwithdraw(self, money):"""取钱"""withself.condition:while money > self.balance:self.condition.wait()            new_balance = self.balance - money            sleep(0.001)self.balance = new_balancedefdeposit(self, money):"""存钱"""withself.condition:            new_balance = self.balance + money            sleep(0.001)self.balance = new_balanceself.condition.notify_all()defadd_money(account):whileTrue:        money = randint(510)        account.deposit(money)print(threading.current_thread().name, ':', money, '====>', account.balance)        sleep(0.5)defsub_money(account):whileTrue:        money = randint(1030)        account.withdraw(money)print(threading.current_thread().name, ':', money, '<====', account.balance)        sleep(1)defmain():    account = Account()with ThreadPoolExecutor(max_workers=15as pool:for _ inrange(5):            pool.submit(add_money, account)for _ inrange(10):            pool.submit(sub_money, account)if __name__ == '__main__':    main()
      • • 多进程:多进程可以有效的解决GIL的问题,实现多进程主要的类是Process,其他辅助的类跟threading模块中的类似,进程间共享数据可以使用管道、套接字等,在multiprocessing模块中有一个Queue类,它基于管道和锁机制提供了多个进程共享的队列。下面是官方文档上关于多进程和进程池的一个示例。
      • (2)多进程:利用多核计算素数
        """多进程和进程池的使用多线程因为GIL的存在不能够发挥CPU的多核特性对于计算密集型任务应该考虑使用多进程time python3 example22.pyreal    0m11.512suser    0m39.319ssys     0m0.169s使用多进程后实际执行时间为11.512秒,而用户时间39.319秒约为实际执行时间的4倍这就证明我们的程序通过多进程使用了CPU的多核特性,而且这台计算机配置了4核的CPU"""import concurrent.futuresimport mathPRIMES = [1116281,1297337,104395303,472882027,533000389,817504243,982451653,112272535095293,112582705942171,112272535095293,115280095190773,115797848077099,1099726899285419] * 5defis_prime(n):"""判断素数"""if n % 2 == 0:returnFalse    sqrt_n = int(math.floor(math.sqrt(n)))for i inrange(3, sqrt_n + 12):if n % i == 0:returnFalsereturnTruedefmain():"""主函数"""with concurrent.futures.ProcessPoolExecutor() as executor:for number, prime inzip(PRIMES, executor.map(is_prime, PRIMES)):print('%d is prime: %s' % (number, prime))if __name__ == '__main__':    main()

        重点多线程和多进程的比较

        以下情况需要使用多线程:

        以下情况需要使用多进程:

        1. 1. 程序执行计算密集型任务(如:字节码操作、数据处理、科学计算)。
        2. 2. 程序的输入可以并行的分成块,并且可以将运算结果合并。
        3. 3. 程序在内存使用方面没有任何限制且不强依赖于I/O操作(如:读写文件、套接字等)。
        1. 1. 程序需要维护许多共享的状态(尤其是可变状态),Python中的列表、字典、集合都是线程安全的,所以使用线程而不是进程维护共享状态的代价相对较小。
        2. 2. 程序会花费大量时间在I/O操作上,没有太多并行计算的需求且不需占用太多的内存。
      (3)异步 I/O:async/await 爬取网页标题
      • 异步处理:从调度程序的任务队列中挑选任务,该调度程序以交叉的形式执行这些任务,我们并不能保证任务将以某种顺序去执行,因为执行顺序取决于队列中的一项任务是否愿意将 CPU 处理时间让位给另一项任务。异步任务通常通过多任务协作处理的方式来实现,由于执行时间和顺序的不确定,因此需要通过回调式编程或者future对象来获取任务执行的结果。Python 3 通过asyncio模块和awaitasync关键字(在 Python 3.7 中正式被列为关键字)来支持异步处理。
      """异步I/O - async / await"""import asynciodefnum_generator(m, n):"""指定范围的数字生成器"""yieldfromrange(m, n + 1)asyncdefprime_filter(m, n):"""素数过滤器"""    primes = []for i in num_generator(m, n):        flag = Truefor j inrange(2int(i ** 0.5 + 1)):if i % j == 0:                flag = Falsebreakif flag:print('Prime =>', i)            primes.append(i)await asyncio.sleep(0.001)returntuple(primes)asyncdefsquare_mapper(m, n):"""平方映射器"""    squares = []for i in num_generator(m, n):print('Square =>', i * i)        squares.append(i * i)await asyncio.sleep(0.001)return squaresdefmain():"""主函数"""    loop = asyncio.get_event_loop()    future = asyncio.gather(prime_filter(2100), square_mapper(1100))    future.add_done_callback(lambda x: print(x.result()))    loop.run_until_complete(future)    loop.close()if __name__ == '__main__':    main()

      说明:上面的代码使用get_event_loop函数获得系统默认的事件循环,通过gather函数可以获得一个future对象,future对象的add_done_callback可以添加执行完成时的回调函数,loop对象的run_until_complete方法可以等待通过future对象获得协程执行结果。

      import asyncioimport reimport aiohttpPATTERN = re.compile(r'\<title\>(?P<title>.*)\<\/title\>')asyncdeffetch_page(session, url):asyncwith session.get(url, ssl=Falseas resp:returnawait resp.text()asyncdefshow_title(url):asyncwith aiohttp.ClientSession() as session:        html = await fetch_page(session, url)print(PATTERN.search(html).group('title'))defmain():    urls = ('https://www.python.org/','https://git-scm.com/','https://www.jd.com/','https://www.taobao.com/','https://www.douban.com/')    loop = asyncio.get_event_loop()    cos = [show_title(url) for url in urls]    loop.run_until_complete(asyncio.wait(cos))    loop.close()if __name__ == '__main__':    main()

      重点异步I/O与多进程的比较

      当程序不需要真正的并发性或并行性,而是更多的依赖于异步处理和回调时,asyncio就是一种很好的选择。如果程序中有大量的等待与休眠时,也应该考虑asyncio,它很适合编写没有实时数据处理需求的 Web 应用服务器。

      八、总结

      Python 进阶的核心是从 “实现功能” 到 “优化实现”,关键知识点可总结为:

      1. 高效语法:生成式简化容器创建,避免嵌套列表的浅拷贝陷阱;
      2. 内置模块:heapq/itertools/collections 替代手写复杂逻辑,提升性能;
      3. 算法基础:掌握复杂度分析和经典算法思想,选择最优解;
      4. 函数进阶:利用闭包、装饰器增强函数功能,提升代码复用性;
      5. 面向对象:遵循 SOLID 原则,用元类 / Mixin 扩展类的能力;
      6. 迭代器 / 生成器:按需生成元素,节省内存;
      7. 并发编程:I/O 密集用多线程 / 异步,计算密集用多进程,避开 GIL 陷阱。
      进阶学习的关键是 “实战”—— 将这些知识点融入实际项目,从性能、可读性、可维护性三个维度优化代码,才能真正掌握 Python 的工程化编程能力。
      九、AI工具,提高学习,工作效率:

      国内直接使用顶级AI工具

      谷歌浏览器访问:https://www.nezhasoft.cloud/r/vMPJZr

      最新文章

      随机文章

      基本 文件 流程 错误 SQL 调试
      1. 请求信息 : 2026-02-11 17:30:32 HTTP/2.0 GET : https://f.mffb.com.cn/a/474997.html
      2. 运行时间 : 0.178910s [ 吞吐率:5.59req/s ] 内存消耗:4,876.15kb 文件加载:140
      3. 缓存信息 : 0 reads,0 writes
      4. 会话信息 : SESSION_ID=c971c1bcf64e7576f35debc58abc972a
      1. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/public/index.php ( 0.79 KB )
      2. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/autoload.php ( 0.17 KB )
      3. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_real.php ( 2.49 KB )
      4. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/platform_check.php ( 0.90 KB )
      5. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/ClassLoader.php ( 14.03 KB )
      6. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_static.php ( 4.90 KB )
      7. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper.php ( 8.34 KB )
      8. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/helper.php ( 2.19 KB )
      9. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/helper.php ( 1.47 KB )
      10. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/stubs/load_stubs.php ( 0.16 KB )
      11. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Exception.php ( 1.69 KB )
      12. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Facade.php ( 2.71 KB )
      13. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/deprecation-contracts/function.php ( 0.99 KB )
      14. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap.php ( 8.26 KB )
      15. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap80.php ( 9.78 KB )
      16. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/Resources/functions/dump.php ( 1.49 KB )
      17. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-dumper/src/helper.php ( 0.18 KB )
      18. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/VarDumper.php ( 4.30 KB )
      19. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/App.php ( 15.30 KB )
      20. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Container.php ( 15.76 KB )
      21. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/container/src/ContainerInterface.php ( 1.02 KB )
      22. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/provider.php ( 0.19 KB )
      23. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Http.php ( 6.04 KB )
      24. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Str.php ( 7.29 KB )
      25. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Env.php ( 4.68 KB )
      26. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/common.php ( 0.03 KB )
      27. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/helper.php ( 18.78 KB )
      28. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Config.php ( 5.54 KB )
      29. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/app.php ( 0.95 KB )
      30. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cache.php ( 0.78 KB )
      31. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/console.php ( 0.23 KB )
      32. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cookie.php ( 0.56 KB )
      33. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/database.php ( 2.48 KB )
      34. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Env.php ( 1.67 KB )
      35. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/filesystem.php ( 0.61 KB )
      36. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/lang.php ( 0.91 KB )
      37. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/log.php ( 1.35 KB )
      38. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/middleware.php ( 0.19 KB )
      39. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/route.php ( 1.89 KB )
      40. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/session.php ( 0.57 KB )
      41. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/trace.php ( 0.34 KB )
      42. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/view.php ( 0.82 KB )
      43. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/event.php ( 0.25 KB )
      44. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Event.php ( 7.67 KB )
      45. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/service.php ( 0.13 KB )
      46. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/AppService.php ( 0.26 KB )
      47. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Service.php ( 1.64 KB )
      48. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Lang.php ( 7.35 KB )
      49. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/lang/zh-cn.php ( 13.70 KB )
      50. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/Error.php ( 3.31 KB )
      51. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/RegisterService.php ( 1.33 KB )
      52. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/services.php ( 0.14 KB )
      53. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/PaginatorService.php ( 1.52 KB )
      54. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ValidateService.php ( 0.99 KB )
      55. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ModelService.php ( 2.04 KB )
      56. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Service.php ( 0.77 KB )
      57. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Middleware.php ( 6.72 KB )
      58. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/BootService.php ( 0.77 KB )
      59. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Paginator.php ( 11.86 KB )
      60. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/Validate.php ( 63.20 KB )
      61. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Model.php ( 23.55 KB )
      62. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Attribute.php ( 21.05 KB )
      63. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/AutoWriteData.php ( 4.21 KB )
      64. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Conversion.php ( 6.44 KB )
      65. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/DbConnect.php ( 5.16 KB )
      66. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/ModelEvent.php ( 2.33 KB )
      67. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/RelationShip.php ( 28.29 KB )
      68. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Arrayable.php ( 0.09 KB )
      69. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Jsonable.php ( 0.13 KB )
      70. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/contract/Modelable.php ( 0.09 KB )
      71. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Db.php ( 2.88 KB )
      72. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/DbManager.php ( 8.52 KB )
      73. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Log.php ( 6.28 KB )
      74. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Manager.php ( 3.92 KB )
      75. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerTrait.php ( 2.69 KB )
      76. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerInterface.php ( 2.71 KB )
      77. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cache.php ( 4.92 KB )
      78. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/simple-cache/src/CacheInterface.php ( 4.71 KB )
      79. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Arr.php ( 16.63 KB )
      80. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/driver/File.php ( 7.84 KB )
      81. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/Driver.php ( 9.03 KB )
      82. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/CacheHandlerInterface.php ( 1.99 KB )
      83. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/Request.php ( 0.09 KB )
      84. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Request.php ( 55.78 KB )
      85. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/middleware.php ( 0.25 KB )
      86. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Pipeline.php ( 2.61 KB )
      87. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/TraceDebug.php ( 3.40 KB )
      88. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/middleware/SessionInit.php ( 1.94 KB )
      89. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Session.php ( 1.80 KB )
      90. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/driver/File.php ( 6.27 KB )
      91. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/SessionHandlerInterface.php ( 0.87 KB )
      92. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/Store.php ( 7.12 KB )
      93. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Route.php ( 23.73 KB )
      94. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleName.php ( 5.75 KB )
      95. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Domain.php ( 2.53 KB )
      96. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleGroup.php ( 22.43 KB )
      97. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Rule.php ( 26.95 KB )
      98. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleItem.php ( 9.78 KB )
      99. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/route/app.php ( 1.72 KB )
      100. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Route.php ( 4.70 KB )
      101. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/dispatch/Controller.php ( 4.74 KB )
      102. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Dispatch.php ( 10.44 KB )
      103. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/controller/Index.php ( 4.81 KB )
      104. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/BaseController.php ( 2.05 KB )
      105. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/facade/Db.php ( 0.93 KB )
      106. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/connector/Mysql.php ( 5.44 KB )
      107. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/PDOConnection.php ( 52.47 KB )
      108. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Connection.php ( 8.39 KB )
      109. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/ConnectionInterface.php ( 4.57 KB )
      110. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/builder/Mysql.php ( 16.58 KB )
      111. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Builder.php ( 24.06 KB )
      112. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseBuilder.php ( 27.50 KB )
      113. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Query.php ( 15.71 KB )
      114. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseQuery.php ( 45.13 KB )
      115. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TimeFieldQuery.php ( 7.43 KB )
      116. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/AggregateQuery.php ( 3.26 KB )
      117. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ModelRelationQuery.php ( 20.07 KB )
      118. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ParamsBind.php ( 3.66 KB )
      119. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ResultOperation.php ( 7.01 KB )
      120. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/WhereQuery.php ( 19.37 KB )
      121. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/JoinAndViewQuery.php ( 7.11 KB )
      122. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TableFieldInfo.php ( 2.63 KB )
      123. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/Transaction.php ( 2.77 KB )
      124. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/driver/File.php ( 5.96 KB )
      125. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/LogHandlerInterface.php ( 0.86 KB )
      126. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/Channel.php ( 3.89 KB )
      127. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/event/LogRecord.php ( 1.02 KB )
      128. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/Collection.php ( 16.47 KB )
      129. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/View.php ( 1.70 KB )
      130. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/View.php ( 4.39 KB )
      131. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Response.php ( 8.81 KB )
      132. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/response/View.php ( 3.29 KB )
      133. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cookie.php ( 6.06 KB )
      134. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-view/src/Think.php ( 8.38 KB )
      135. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/TemplateHandlerInterface.php ( 1.60 KB )
      136. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/Template.php ( 46.61 KB )
      137. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/driver/File.php ( 2.41 KB )
      138. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/contract/DriverInterface.php ( 0.86 KB )
      139. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/runtime/temp/067d451b9a0c665040f3f1bdd3293d68.php ( 11.98 KB )
      140. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Html.php ( 4.42 KB )
      1. CONNECT:[ UseTime:0.000901s ] mysql:host=127.0.0.1;port=3306;dbname=f_mffb;charset=utf8mb4
      2. SHOW FULL COLUMNS FROM `fenlei` [ RunTime:0.001246s ]
      3. SELECT * FROM `fenlei` WHERE `fid` = 0 [ RunTime:0.000450s ]
      4. SELECT * FROM `fenlei` WHERE `fid` = 63 [ RunTime:0.000447s ]
      5. SHOW FULL COLUMNS FROM `set` [ RunTime:0.000855s ]
      6. SELECT * FROM `set` [ RunTime:0.003298s ]
      7. SHOW FULL COLUMNS FROM `article` [ RunTime:0.000965s ]
      8. SELECT * FROM `article` WHERE `id` = 474997 LIMIT 1 [ RunTime:0.001170s ]
      9. UPDATE `article` SET `lasttime` = 1770802232 WHERE `id` = 474997 [ RunTime:0.021084s ]
      10. SELECT * FROM `fenlei` WHERE `id` = 66 LIMIT 1 [ RunTime:0.001659s ]
      11. SELECT * FROM `article` WHERE `id` < 474997 ORDER BY `id` DESC LIMIT 1 [ RunTime:0.007491s ]
      12. SELECT * FROM `article` WHERE `id` > 474997 ORDER BY `id` ASC LIMIT 1 [ RunTime:0.000666s ]
      13. SELECT * FROM `article` WHERE `id` < 474997 ORDER BY `id` DESC LIMIT 10 [ RunTime:0.001807s ]
      14. SELECT * FROM `article` WHERE `id` < 474997 ORDER BY `id` DESC LIMIT 10,10 [ RunTime:0.004935s ]
      15. SELECT * FROM `article` WHERE `id` < 474997 ORDER BY `id` DESC LIMIT 20,10 [ RunTime:0.017052s ]
      0.181653s