Python语言进阶

重要知识点

  • 生成式(推导式)的用法
    1. prices = {
    2. 'AAPL': 191.88,
    3. 'GOOG': 1186.96,
    4. 'IBM': 149.24,
    5. 'ORCL': 48.44,
    6. 'ACN': 166.89,
    7. 'FB': 208.09,
    8. 'SYMC': 21.29
    9. }
    10. # 用股票价格大于100元的股票构造一个新的字典
    11. prices2 = {key: value for key, value in prices.items() if value > 100}
    12. print(prices2)

说明:生成式(推导式)可以用来生成列表、集合和字典。

  • 嵌套的列表的坑
    1. names = ['关羽', '张飞', '赵云', '马超', '黄忠']
    2. courses = ['语文', '数学', '英语']
    3. # 录入五个学生三门课程的成绩
    4. # 错误 - 参考http://pythontutor.com/visualize.html#mode=edit
    5. # scores = [[None] * len(courses)] * len(names)
    6. scores = [[None] * len(courses) for _ in range(len(names))]
    7. for row, name in enumerate(names):
    8. for col, course in enumerate(courses):
    9. scores[row][col] = float(input(f'请输入{name}的{course}成绩: '))
    10. print(scores)


Python Tutor - VISUALIZE CODE AND GET LIVE HELP

  • heapq模块(堆排序) ```python “”” 从列表中找出最大的或最小的N个元素 堆结构(大根堆/小根堆) “”” import heapq

list1 = [34, 25, 12, 99, 87, 63, 58, 78, 88, 92] 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’]))

  1. -
  2. `itertools`模块
  3. ```python
  4. """
  5. 迭代工具模块
  6. """
  7. import itertools
  8. # 产生ABCD的全排列
  9. itertools.permutations('ABCD')
  10. # 产生ABCDE的五选三组合
  11. itertools.combinations('ABCDE', 3)
  12. # 产生ABCD和123的笛卡尔积
  13. itertools.product('ABCD', '123')
  14. # 产生ABC的无限循环序列
  15. itertools.cycle(('A', 'B', 'C'))
  • collections模块
    常用的工具类:

    • namedtuple:命令元组,它是一个类工厂,接受类型的名称和属性列表来创建一个类。
    • deque:双端队列,是列表的替代实现。Python中的列表底层是基于数组来实现的,而deque底层是双向链表,因此当你需要在头尾添加和删除元素时,deque会表现出更好的性能,渐近时间复杂度为16-20.Python语言进阶 - 图1#card=math&code=O%281%29)。
    • Counterdict的子类,键是元素,值是元素的计数,它的most_common()方法可以帮助我们获取出现频率最高的元素。Counterdict的继承关系我认为是值得商榷的,按照CARP原则,Counterdict的关系应该设计为关联关系更为合理。
    • OrderedDictdict的子类,它记录了键值对插入的顺序,看起来既有字典的行为,也有链表的行为。
    • defaultdict:类似于字典类型,但是可以通过默认的工厂函数来获得键对应的默认值,相比字典中的setdefault()方法,这种做法更加高效。 ```python “”” 找出序列中出现次数最多的元素 “”” from collections import Counter

words = [ ‘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))

  1. <a name="31ea1cbb"></a>
  2. ### 数据结构和算法
  3. -
  4. 算法:解决问题的方法和步骤
  5. -
  6. 评价算法的好坏:渐近时间复杂度和渐近空间复杂度。
  7. -
  8. 渐近时间复杂度的大O标记:
  9. - ![](http://latex.codecogs.com/gif.latex?O(c)#) - 常量时间复杂度 - 布隆过滤器 / 哈希存储
  10. - ![](http://latex.codecogs.com/gif.latex?O(log_2n)#) - 对数时间复杂度 - 折半查找(二分查找)
  11. - ![](http://latex.codecogs.com/gif.latex?O(n)#) - 线性时间复杂度 - 顺序查找 / 计数排序
  12. - ![](http://latex.codecogs.com/gif.latex?O(n*log_2n)#) - 对数线性时间复杂度 - 高级排序算法(归并排序、快速排序)
  13. - ![](http://latex.codecogs.com/gif.latex?O(n^2)#) - 平方时间复杂度 - 简单排序算法(选择排序、插入排序、冒泡排序)
  14. - ![](http://latex.codecogs.com/gif.latex?O(n^3)#) - 立方时间复杂度 - Floyd算法 / 矩阵乘法运算
  15. - ![](http://latex.codecogs.com/gif.latex?O(2^n)#) - 几何级数时间复杂度 - 汉诺塔
  16. - ![](http://latex.codecogs.com/gif.latex?O(n!)#) - 阶乘时间复杂度 - 旅行经销商问题 - NPC
  17. ![](./res/algorithm_complexity_1.png#alt=)
  18. ![](./res/algorithm_complexity_2.png#alt=)
  19. -
  20. 排序算法(选择、冒泡和归并)和查找算法(顺序和折半)
  21. ```python
  22. def select_sort(items, comp=lambda x, y: x < y):
  23. """简单选择排序"""
  24. items = items[:]
  25. for i in range(len(items) - 1):
  26. min_index = i
  27. for j in range(i + 1, len(items)):
  28. if comp(items[j], items[min_index]):
  29. min_index = j
  30. items[i], items[min_index] = items[min_index], items[i]
  31. return items
  1. def bubble_sort(items, comp=lambda x, y: x > y):
  2. """冒泡排序"""
  3. items = items[:]
  4. for i in range(len(items) - 1):
  5. swapped = False
  6. for j in range(len(items) - 1 - i):
  7. if comp(items[j], items[j + 1]):
  8. items[j], items[j + 1] = items[j + 1], items[j]
  9. swapped = True
  10. if not swapped:
  11. break
  12. return items
  1. def bubble_sort(items, comp=lambda x, y: x > y):
  2. """搅拌排序(冒泡排序升级版)"""
  3. items = items[:]
  4. for i in range(len(items) - 1):
  5. swapped = False
  6. for j in range(len(items) - 1 - i):
  7. if comp(items[j], items[j + 1]):
  8. items[j], items[j + 1] = items[j + 1], items[j]
  9. swapped = True
  10. if swapped:
  11. swapped = False
  12. for j in range(len(items) - 2 - i, i, -1):
  13. if comp(items[j - 1], items[j]):
  14. items[j], items[j - 1] = items[j - 1], items[j]
  15. swapped = True
  16. if not swapped:
  17. break
  18. return items
  1. def merge(items1, items2, comp=lambda x, y: x < y):
  2. """合并(将两个有序的列表合并成一个有序的列表)"""
  3. items = []
  4. index1, index2 = 0, 0
  5. while index1 < len(items1) and index2 < len(items2):
  6. if comp(items1[index1], items2[index2]):
  7. items.append(items1[index1])
  8. index1 += 1
  9. else:
  10. items.append(items2[index2])
  11. index2 += 1
  12. items += items1[index1:]
  13. items += items2[index2:]
  14. return items
  15. def merge_sort(items, comp=lambda x, y: x < y):
  16. return _merge_sort(list(items), comp)
  17. def _merge_sort(items, comp):
  18. """归并排序"""
  19. if len(items) < 2:
  20. return items
  21. mid = len(items) // 2
  22. left = _merge_sort(items[:mid], comp)
  23. right = _merge_sort(items[mid:], comp)
  24. return merge(left, right, comp)
  1. def seq_search(items, key):
  2. """顺序查找"""
  3. for index, item in enumerate(items):
  4. if item == key:
  5. return index
  6. return -1
  1. def bin_search(items, key):
  2. """折半查找"""
  3. start, end = 0, len(items) - 1
  4. while start <= end:
  5. mid = (start + end) // 2
  6. if key > items[mid]:
  7. start = mid + 1
  8. elif key < items[mid]:
  9. end = mid - 1
  10. else:
  11. return mid
  12. return -1
  • 常用算法:

    • 穷举法 - 又称为暴力破解法,对所有的可能性进行验证,直到找到正确答案。
    • 贪婪法 - 在对问题求解时,总是做出在当前看来
    • 最好的选择,不追求最优解,快速找到满意解。
    • 分治法 - 把一个复杂的问题分成两个或更多的相同或相似的子问题,再把子问题分成更小的子问题,直到可以直接求解的程度,最后将子问题的解进行合并得到原问题的解。
    • 回溯法 - 回溯法又称为试探法,按选优条件向前搜索,当搜索到某一步发现原先选择并不优或达不到目标时,就退回一步重新选择。
    • 动态规划 - 基本思想也是将待求解问题分解成若干个子问题,先求解并保存这些子问题的解,避免产生大量的重复运算。
  1. # 公鸡5元一只 母鸡3元一只 小鸡1元三只
  2. # 用100元买100只鸡 问公鸡/母鸡/小鸡各多少只
  3. for x in range(20):
  4. for y in range(33):
  5. z = 100 - x - y
  6. if 5 * x + 3 * y + z // 3 == 100 and z % 3 == 0:
  7. print(x, y, z)
  8. # A、B、C、D、E五人在某天夜里合伙捕鱼 最后疲惫不堪各自睡觉
  9. # 第二天A第一个醒来 他将鱼分为5份 扔掉多余的1条 拿走自己的一份
  10. # B第二个醒来 也将鱼分为5份 扔掉多余的1条 拿走自己的一份
  11. # 然后C、D、E依次醒来也按同样的方式分鱼 问他们至少捕了多少条鱼
  12. fish = 6
  13. while True:
  14. total = fish
  15. enough = True
  16. for _ in range(5):
  17. if (total - 1) % 5 == 0:
  18. total = (total - 1) // 5 * 4
  19. else:
  20. enough = False
  21. break
  22. if enough:
  23. print(fish)
  24. break
  25. fish += 5
名称 价格(美元) 重量(kg)
电脑 200 20
收音机 20 4
175 10
花瓶 50 2
10 1
油画 90 9
  1. """
  2. 贪婪法:在对问题求解时,总是做出在当前看来是最好的选择,不追求最优解,快速找到满意解。
  3. 输入:
  4. 20 6
  5. 电脑 200 20
  6. 收音机 20 4
  7. 钟 175 10
  8. 花瓶 50 2
  9. 书 10 1
  10. 油画 90 9
  11. """
  12. class Thing(object):
  13. """物品"""
  14. def __init__(self, name, price, weight):
  15. self.name = name
  16. self.price = price
  17. self.weight = weight
  18. @property
  19. def value(self):
  20. """价格重量比"""
  21. return self.price / self.weight
  22. def input_thing():
  23. """输入物品信息"""
  24. name_str, price_str, weight_str = input().split()
  25. return name_str, int(price_str), int(weight_str)
  26. def main():
  27. """主函数"""
  28. max_weight, num_of_things = map(int, input().split())
  29. all_things = []
  30. for _ in range(num_of_things):
  31. all_things.append(Thing(*input_thing()))
  32. all_things.sort(key=lambda x: x.value, reverse=True)
  33. total_weight = 0
  34. total_price = 0
  35. for thing in all_things:
  36. if total_weight + thing.weight <= max_weight:
  37. print(f'小偷拿走了{thing.name}')
  38. total_weight += thing.weight
  39. total_price += thing.price
  40. print(f'总价值: {total_price}美元')
  41. if __name__ == '__main__':
  42. main()

快速排序```python “”” 快速排序 - 选择枢轴对元素进行划分,左边都比枢轴小右边都比枢轴大 “”” def quick_sort(items, comp=lambda x, y: x <= y): items = list(items)[:] _quick_sort(items, 0, len(items) - 1, comp) return items

def _quick_sort(items, start, end, comp): if start < end: pos = _partition(items, start, end, comp) _quick_sort(items, start, pos - 1, comp) _quick_sort(items, pos + 1, end, comp)

def _partition(items, start, end, comp): pivot = items[end] i = start - 1 for j in range(start, end): if comp(items[j], pivot): i += 1 items[i], items[j] = items[j], items[i] items[i + 1], items[end] = items[end], items[i + 1] return i + 1

  1. [骑士巡逻](https://zh.wikipedia.org/zh/%E9%AA%91%E5%A3%AB%E5%B7%A1%E9%80%BB)```python
  2. """
  3. 递归回溯法:叫称为试探法,按选优条件向前搜索,当搜索到某一步,发现原先选择并不优或达不到目标时,就退回一步重新选择,比较经典的问题包括骑士巡逻、八皇后和迷宫寻路等。
  4. """
  5. import sys
  6. import time
  7. SIZE = 5
  8. total = 0
  9. def print_board(board):
  10. for row in board:
  11. for col in row:
  12. print(str(col).center(4), end='')
  13. print()
  14. def patrol(board, row, col, step=1):
  15. if row >= 0 and row < SIZE and \
  16. col >= 0 and col < SIZE and \
  17. board[row][col] == 0:
  18. board[row][col] = step
  19. if step == SIZE * SIZE:
  20. global total
  21. total += 1
  22. print(f'第{total}种走法: ')
  23. print_board(board)
  24. patrol(board, row - 2, col - 1, step + 1)
  25. patrol(board, row - 1, col - 2, step + 1)
  26. patrol(board, row + 1, col - 2, step + 1)
  27. patrol(board, row + 2, col - 1, step + 1)
  28. patrol(board, row + 2, col + 1, step + 1)
  29. patrol(board, row + 1, col + 2, step + 1)
  30. patrol(board, row - 1, col + 2, step + 1)
  31. patrol(board, row - 2, col + 1, step + 1)
  32. board[row][col] = 0
  33. def main():
  34. board = [[0] * SIZE for _ in range(SIZE)]
  35. patrol(board, SIZE - 1, SIZE - 1)
  36. if __name__ == '__main__':
  37. main()

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

输入:1 -2 3 5 -3 2

输出:8

输入:0 -2 3 5 -1 2

输出:9

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

输出:-2

  1. def main():
  2. items = list(map(int, input().split()))
  3. overall = partial = items[0]
  4. for i in range(1, len(items)):
  5. partial = max(items[i], partial + items[i])
  6. overall = max(partial, overall)
  7. print(overall)
  8. if __name__ == '__main__':
  9. main()

说明:这个题目最容易想到的解法是使用二重循环,但是代码的时间性能将会变得非常的糟糕。使用动态规划的思想,仅仅是多用了两个变量,就将原来16-20.Python语言进阶 - 图2#card=math&code=O%28N%5E2%29)复杂度的问题变成了16-20.Python语言进阶 - 图3#card=math&code=O%28N%29)。

函数的使用方式

  • 将函数视为“一等公民”

    • 函数可以赋值给变量
    • 函数可以作为函数的参数
    • 函数可以作为函数的返回值
  • 高阶函数的用法(filtermap以及它们的替代品)
    1. items1 = list(map(lambda x: x ** 2, filter(lambda x: x % 2, range(1, 10))))
    2. items2 = [x ** 2 for x in range(1, 10) if x % 2]
  • 位置参数、可变参数、关键字参数、命名关键字参数

  • 参数的元信息(代码可读性问题)

  • 匿名函数和内联函数的用法(lambda函数)

  • 闭包和作用域问题

    • Python搜索变量的LEGB顺序(Local >>> Embedded >>> Global >>> Built-in)

    • globalnonlocal关键字的作用
      global:声明或定义全局变量(要么直接使用现有的全局作用域的变量,要么定义一个变量放到全局作用域)。
      nonlocal:声明使用嵌套作用域的变量(嵌套作用域必须存在该变量,否则报错)。

  • 装饰器函数(使用装饰器和取消装饰器)
    例子:输出函数执行时间的装饰器。

    1. def record_time(func):
    2. """自定义装饰函数的装饰器"""
    3. @wraps(func)
    4. def wrapper(*args, **kwargs):
    5. start = time()
    6. result = func(*args, **kwargs)
    7. print(f'{func.__name__}: {time() - start}秒')
    8. return result
    9. return wrapper


如果装饰器不希望跟print函数耦合,可以编写可以参数化的装饰器。

  1. from functools import wraps
  2. from time import time
  3. def record(output):
  4. """可以参数化的装饰器"""
  5. def decorate(func):
  6. @wraps(func)
  7. def wrapper(*args, **kwargs):
  8. start = time()
  9. result = func(*args, **kwargs)
  10. output(func.__name__, time() - start)
  11. return result
  12. return wrapper
  13. return decorate
  1. from functools import wraps
  2. from time import time
  3. class Record():
  4. """通过定义类的方式定义装饰器"""
  5. def __init__(self, output):
  6. self.output = output
  7. def __call__(self, func):
  8. @wraps(func)
  9. def wrapper(*args, **kwargs):
  10. start = time()
  11. result = func(*args, **kwargs)
  12. self.output(func.__name__, time() - start)
  13. return result
  14. return wrapper

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


例子:用装饰器来实现单例模式。

  1. from functools import wraps
  2. def singleton(cls):
  3. """装饰类的装饰器"""
  4. instances = {}
  5. @wraps(cls)
  6. def wrapper(*args, **kwargs):
  7. if cls not in instances:
  8. instances[cls] = cls(*args, **kwargs)
  9. return instances[cls]
  10. return wrapper
  11. @singleton
  12. class President:
  13. """总统(单例类)"""
  14. pass

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


线程安全的单例装饰器。

  1. from functools import wraps
  2. from threading import RLock
  3. def singleton(cls):
  4. """线程安全的单例装饰器"""
  5. instances = {}
  6. locker = RLock()
  7. @wraps(cls)
  8. def wrapper(*args, **kwargs):
  9. if cls not in instances:
  10. with locker:
  11. if cls not in instances:
  12. instances[cls] = cls(*args, **kwargs)
  13. return instances[cls]
  14. return wrapper

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

面向对象相关知识

  • 三大支柱:封装、继承、多态
    例子:工资结算系统。 ```python “”” 月薪结算系统 - 部门经理每月15000 程序员每小时200 销售员1800底薪加销售额5%提成 “”” from abc import ABCMeta, abstractmethod

class Employee(metaclass=ABCMeta): “””员工(抽象类)”””

  1. def __init__(self, name):
  2. self.name = name
  3. @abstractmethod
  4. def get_salary(self):
  5. """结算月薪(抽象方法)"""
  6. pass

class Manager(Employee): “””部门经理”””

  1. def get_salary(self):
  2. return 15000.0

class Programmer(Employee): “””程序员”””

  1. def __init__(self, name, working_hour=0):
  2. self.working_hour = working_hour
  3. super().__init__(name)
  4. def get_salary(self):
  5. return 200.0 * self.working_hour

class Salesman(Employee): “””销售员”””

  1. def __init__(self, name, sales=0.0):
  2. self.sales = sales
  3. super().__init__(name)
  4. def get_salary(self):
  5. return 1800.0 + self.sales * 0.05

class EmployeeFactory: “””创建员工的工厂(工厂模式 - 通过工厂实现对象使用者和对象之间的解耦合)”””

  1. @staticmethod
  2. def create(emp_type, *args, **kwargs):
  3. """创建员工"""
  4. all_emp_types = {'M': Manager, 'P': Programmer, 'S': Salesman}
  5. cls = all_emp_types[emp_type.upper()]
  6. return cls(*args, **kwargs) if cls else None

def main(): “””主函数””” 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()

  1. -
  2. 类与类之间的关系
  3. - is-a关系:继承
  4. - has-a关系:关联 / 聚合 / 合成
  5. - use-a关系:依赖
  6. ```python
  7. """
  8. 经验:符号常量总是优于字面常量,枚举类型是定义符号常量的最佳选择
  9. """
  10. from enum import Enum, unique
  11. import random
  12. @unique
  13. class Suite(Enum):
  14. """花色"""
  15. SPADE, HEART, CLUB, DIAMOND = range(4)
  16. def __lt__(self, other):
  17. return self.value < other.value
  18. class Card():
  19. """牌"""
  20. def __init__(self, suite, face):
  21. """初始化方法"""
  22. self.suite = suite
  23. self.face = face
  24. def show(self):
  25. """显示牌面"""
  26. suites = ['♠︎', '♥︎', '♣︎', '♦︎']
  27. faces = ['', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
  28. return f'{suites[self.suite.value]}{faces[self.face]}'
  29. def __repr__(self):
  30. return self.show()
  31. class Poker():
  32. """扑克"""
  33. def __init__(self):
  34. self.index = 0
  35. self.cards = [Card(suite, face)
  36. for suite in Suite
  37. for face in range(1, 14)]
  38. def shuffle(self):
  39. """洗牌(随机乱序)"""
  40. random.shuffle(self.cards)
  41. self.index = 0
  42. def deal(self):
  43. """发牌"""
  44. card = self.cards[self.index]
  45. self.index += 1
  46. return card
  47. @property
  48. def has_more(self):
  49. return self.index < len(self.cards)
  50. class Player():
  51. """玩家"""
  52. def __init__(self, name):
  53. self.name = name
  54. self.cards = []
  55. def get_one(self, card):
  56. """摸一张牌"""
  57. self.cards.append(card)
  58. def sort(self, comp=lambda card: (card.suite, card.face)):
  59. """整理手上的牌"""
  60. self.cards.sort(key=comp)
  61. def main():
  62. """主函数"""
  63. poker = Poker()
  64. poker.shuffle()
  65. players = [Player('东邪'), Player('西毒'), Player('南帝'), Player('北丐')]
  66. while poker.has_more:
  67. for player in players:
  68. player.get_one(poker.deal())
  69. for player in players:
  70. player.sort()
  71. print(player.name, end=': ')
  72. print(player.cards)
  73. if __name__ == '__main__':
  74. main()

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

  • 对象的复制(深复制/深拷贝/深度克隆和浅复制/浅拷贝/影子克隆)

  • 垃圾回收、循环引用和弱引用
    Python使用了自动化内存管理,这种管理机制以引用计数为基础,同时也引入了标记-清除分代收集两种机制为辅的策略。

    1. typedef struct _object {
    2. /* 引用计数 */
    3. int ob_refcnt;
    4. /* 对象指针 */
    5. struct _typeobject *ob_type;
    6. } PyObject;
  1. /* 增加引用计数的宏定义 */
  2. #define Py_INCREF(op) ((op)->ob_refcnt++)
  3. /* 减少引用计数的宏定义 */
  4. #define Py_DECREF(op) \ //减少计数
  5. if (--(op)->ob_refcnt != 0) \
  6. ; \
  7. else \
  8. __Py_Dealloc((PyObject *)(op))


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

  • 对象被创建,例如a = 23
  • 对象被引用,例如b = a
  • 对象被作为参数,传入到一个函数中,例如f(a)
  • 对象作为一个元素,存储在容器中,例如list1 = [a, a]

  • 对象的别名被显式销毁,例如del a

  • 对象的别名被赋予新的对象,例如a = 24
  • 一个对象离开它的作用域,例如f函数执行完毕时,f函数中的局部变量(全局变量不会)
  • 对象所在的容器被销毁,或从容器中删除对象
  1. # 循环引用会导致内存泄露 - Python除了引用技术还引入了标记清理和分代回收
  2. # 在Python 3.6以前如果重写__del__魔术方法会导致循环引用处理失效
  3. # 如果不想造成循环引用可以使用弱引用
  4. list1 = []
  5. list2 = []
  6. list1.append(list2)
  7. list2.append(list1)
  • 调用gc.collect()
  • gc模块的计数器达到阀值
  • 程序退出

__del__``gc``__del__ weakref

  • 魔法属性和方法(请参考《Python魔法方法指南》)
    有几个小问题请大家思考:

    • 自定义的对象能不能使用运算符做运算?
    • 自定义的对象能不能放到set中?能去重吗?
    • 自定义的对象能不能作为dict的键?
    • 自定义的对象能不能使用上下文语法?
  • 混入(Mixin)
    例子:自定义字典限制只有在指定的key不存在时才能在字典中设置键值对。 ```python class SetOnceMappingMixin: “””自定义混入类””” slots = ()

    def setitem(self, key, value):

    1. if key in self:
    2. raise KeyError(str(key) + ' already set')
    3. return super().__setitem__(key, value)

class SetOnceDict(SetOnceMappingMixin, dict): “””自定义字典””” pass

my_dict= SetOnceDict() try: my_dict[‘username’] = ‘jackfrued’ my_dict[‘username’] = ‘hellokitty’ except KeyError: pass print(my_dict)

  1. -
  2. 元编程和元类
  3. <br />对象是通过类创建的,类是通过元类创建的,元类提供了创建类的元信息。所有的类都直接或间接的继承自`object`,所有的元类都直接或间接的继承自`type`
  4. <br />例子:用元类实现单例模式。
  5. ```python
  6. import threading
  7. class SingletonMeta(type):
  8. """自定义元类"""
  9. def __init__(cls, *args, **kwargs):
  10. cls.__instance = None
  11. cls.__lock = threading.RLock()
  12. super().__init__(*args, **kwargs)
  13. def __call__(cls, *args, **kwargs):
  14. if cls.__instance is None:
  15. with cls.__lock:
  16. if cls.__instance is None:
  17. cls.__instance = super().__call__(*args, **kwargs)
  18. return cls.__instance
  19. class President(metaclass=SingletonMeta):
  20. """总统(单例类)"""
  21. pass
  • 面向对象设计原则

    • 单一职责原则 (SRP)- 一个类只做该做的事情(类的设计要高内聚)
    • 开闭原则 (OCP)- 软件实体应该对扩展开发对修改关闭
    • 依赖倒转原则(DIP)- 面向抽象编程(在弱类型语言中已经被弱化)
    • 里氏替换原则(LSP) - 任何时候可以用子类对象替换掉父类对象
    • 接口隔离原则(ISP)- 接口要小而专不要大而全(Python中没有接口的概念)
    • 合成聚合复用原则(CARP) - 优先使用强关联关系而不是继承关系复用代码
    • 最少知识原则(迪米特法则,LoD)- 不要给没有必然联系的对象发消息

      说明:上面加粗的字母放在一起称为面向对象的SOLID原则。

  • GoF设计模式

    • 创建型模式:单例、工厂、建造者、原型
    • 结构型模式:适配器、门面(外观)、代理
    • 行为型模式:迭代器、观察者、状态、策略
  1. class StreamHasher():
  2. """哈希摘要生成器"""
  3. def __init__(self, alg='md5', size=4096):
  4. self.size = size
  5. alg = alg.lower()
  6. self.hasher = getattr(__import__('hashlib'), alg.lower())()
  7. def __call__(self, stream):
  8. return self.to_digest(stream)
  9. def to_digest(self, stream):
  10. """生成十六进制形式的摘要"""
  11. for buf in iter(lambda: stream.read(self.size), b''):
  12. self.hasher.update(buf)
  13. return self.hasher.hexdigest()
  14. def main():
  15. """主函数"""
  16. hasher1 = StreamHasher()
  17. with open('Python-3.7.6.tgz', 'rb') as stream:
  18. print(hasher1.to_digest(stream))
  19. hasher2 = StreamHasher('sha1')
  20. with open('Python-3.7.6.tgz', 'rb') as stream:
  21. print(hasher2(stream))
  22. if __name__ == '__main__':
  23. main()

迭代器和生成器

  • 迭代器是实现了迭代器协议的对象。

    • Python中没有像protocolinterface这样的定义协议的关键字。
    • Python中用魔术方法表示协议。
    • __iter____next__魔术方法就是迭代器协议。

      1. class Fib(object):
      2. """迭代器"""
      3. def __init__(self, num):
      4. self.num = num
      5. self.a, self.b = 0, 1
      6. self.idx = 0
      7. def __iter__(self):
      8. return self
      9. def __next__(self):
      10. if self.idx < self.num:
      11. self.a, self.b = self.b, self.a + self.b
      12. self.idx += 1
      13. return self.a
      14. raise StopIteration()
  • 生成器是语法简化版的迭代器。

    1. def fib(num):
    2. """生成器"""
    3. a, b = 0, 1
    4. for _ in range(num):
    5. a, b = b, a + b
    6. yield a
  • 生成器进化为协程。
    生成器对象可以使用send()方法发送数据,发送的数据会成为生成器函数中通过yield表达式获得的值。这样,生成器就可以作为协程使用,协程简单的说就是可以相互协作的子程序。 ```python def calc_avg(): “””流式计算平均值””” total, counter = 0, 0 avg_value = None while True:
    1. value = yield avg_value
    2. total, counter = total + value, counter + 1
    3. avg_value = total / counter

gen = calc_avg() next(gen) print(gen.send(10)) print(gen.send(20)) print(gen.send(30))

  1. <a name="1a9a671b"></a>
  2. ### 并发编程
  3. Python中实现并发编程的三种方案:多线程、多进程和异步I/O。并发编程的好处在于可以提升程序的执行效率以及改善用户体验;坏处在于并发的程序不容易开发和调试,同时对其他程序来说它并不友好。
  4. -
  5. 多线程:Python中提供了`Thread`类并辅以`Lock`、`Condition`、`Event`、`Semaphore`和`Barrier`。Python中有GIL来防止多个线程同时执行本地字节码,这个锁对于CPython是必须的,因为CPython的内存管理并不是线程安全的,因为GIL的存在多线程并不能发挥CPU的多核特性。
  6. ```python
  7. """
  8. 面试题:进程和线程的区别和联系?
  9. 进程 - 操作系统分配内存的基本单位 - 一个进程可以包含一个或多个线程
  10. 线程 - 操作系统分配CPU的基本单位
  11. 并发编程(concurrent programming)
  12. 1. 提升执行性能 - 让程序中没有因果关系的部分可以并发的执行
  13. 2. 改善用户体验 - 让耗时间的操作不会造成程序的假死
  14. """
  15. import glob
  16. import os
  17. import threading
  18. from PIL import Image
  19. PREFIX = 'thumbnails'
  20. def generate_thumbnail(infile, size, format='PNG'):
  21. """生成指定图片文件的缩略图"""
  22. file, ext = os.path.splitext(infile)
  23. file = file[file.rfind('/') + 1:]
  24. outfile = f'{PREFIX}/{file}_{size[0]}_{size[1]}.{ext}'
  25. img = Image.open(infile)
  26. img.thumbnail(size, Image.ANTIALIAS)
  27. img.save(outfile, format)
  28. def main():
  29. """主函数"""
  30. if not os.path.exists(PREFIX):
  31. os.mkdir(PREFIX)
  32. for infile in glob.glob('images/*.png'):
  33. for size in (32, 64, 128):
  34. # 创建并启动线程
  35. threading.Thread(
  36. target=generate_thumbnail,
  37. args=(infile, (size, size))
  38. ).start()
  39. if __name__ == '__main__':
  40. main()


多个线程竞争资源的情况。

  1. """
  2. 多线程程序如果没有竞争资源处理起来通常也比较简单
  3. 当多个线程竞争临界资源的时候如果缺乏必要的保护措施就会导致数据错乱
  4. 说明:临界资源就是被多个线程竞争的资源
  5. """
  6. import time
  7. import threading
  8. from concurrent.futures import ThreadPoolExecutor
  9. class Account(object):
  10. """银行账户"""
  11. def __init__(self):
  12. self.balance = 0.0
  13. self.lock = threading.Lock()
  14. def deposit(self, money):
  15. # 通过锁保护临界资源
  16. with self.lock:
  17. new_balance = self.balance + money
  18. time.sleep(0.001)
  19. self.balance = new_balance
  20. def main():
  21. """主函数"""
  22. account = Account()
  23. # 创建线程池
  24. pool = ThreadPoolExecutor(max_workers=10)
  25. futures = []
  26. for _ in range(100):
  27. future = pool.submit(account.deposit, 1)
  28. futures.append(future)
  29. # 关闭线程池
  30. pool.shutdown()
  31. for future in futures:
  32. future.result()
  33. print(account.balance)
  34. if __name__ == '__main__':
  35. main()


修改上面的程序,启动5个线程向账户中存钱,5个线程从账户中取钱,取钱时如果余额不足就暂停线程进行等待。为了达到上述目标,需要对存钱和取钱的线程进行调度,在余额不足时取钱的线程暂停并释放锁,而存钱的线程将钱存入后要通知取钱的线程,使其从暂停状态被唤醒。可以使用threading模块的Condition来实现线程调度,该对象也是基于锁来创建的,代码如下所示:

  1. """
  2. 多个线程竞争一个资源 - 保护临界资源 - 锁(Lock/RLock)
  3. 多个线程竞争多个资源(线程数>资源数) - 信号量(Semaphore)
  4. 多个线程的调度 - 暂停线程执行/唤醒等待中的线程 - Condition
  5. """
  6. from concurrent.futures import ThreadPoolExecutor
  7. from random import randint
  8. from time import sleep
  9. import threading
  10. class Account:
  11. """银行账户"""
  12. def __init__(self, balance=0):
  13. self.balance = balance
  14. lock = threading.RLock()
  15. self.condition = threading.Condition(lock)
  16. def withdraw(self, money):
  17. """取钱"""
  18. with self.condition:
  19. while money > self.balance:
  20. self.condition.wait()
  21. new_balance = self.balance - money
  22. sleep(0.001)
  23. self.balance = new_balance
  24. def deposit(self, money):
  25. """存钱"""
  26. with self.condition:
  27. new_balance = self.balance + money
  28. sleep(0.001)
  29. self.balance = new_balance
  30. self.condition.notify_all()
  31. def add_money(account):
  32. while True:
  33. money = randint(5, 10)
  34. account.deposit(money)
  35. print(threading.current_thread().name,
  36. ':', money, '====>', account.balance)
  37. sleep(0.5)
  38. def sub_money(account):
  39. while True:
  40. money = randint(10, 30)
  41. account.withdraw(money)
  42. print(threading.current_thread().name,
  43. ':', money, '<====', account.balance)
  44. sleep(1)
  45. def main():
  46. account = Account()
  47. with ThreadPoolExecutor(max_workers=15) as pool:
  48. for _ in range(5):
  49. pool.submit(add_money, account)
  50. for _ in range(10):
  51. pool.submit(sub_money, account)
  52. if __name__ == '__main__':
  53. main()
  • 多进程:多进程可以有效的解决GIL的问题,实现多进程主要的类是Process,其他辅助的类跟threading模块中的类似,进程间共享数据可以使用管道、套接字等,在multiprocessing模块中有一个Queue类,它基于管道和锁机制提供了多个进程共享的队列。下面是官方文档上关于多进程和进程池的一个示例。 ```python “”” 多进程和进程池的使用 多线程因为GIL的存在不能够发挥CPU的多核特性 对于计算密集型任务应该考虑使用多进程 time python3 example22.py real 0m11.512s user 0m39.319s sys 0m0.169s 使用多进程后实际执行时间为11.512秒,而用户时间39.319秒约为实际执行时间的4倍 这就证明我们的程序通过多进程使用了CPU的多核特性,而且这台计算机配置了4核的CPU “”” import concurrent.futures import math

PRIMES = [ 1116281, 1297337, 104395303, 472882027, 533000389, 817504243, 982451653, 112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419 ] * 5

def is_prime(n): “””判断素数””” if n % 2 == 0: return False

  1. sqrt_n = int(math.floor(math.sqrt(n)))
  2. for i in range(3, sqrt_n + 1, 2):
  3. if n % i == 0:
  4. return False
  5. return True

def main(): “””主函数””” with concurrent.futures.ProcessPoolExecutor() as executor: for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)): print(‘%d is prime: %s’ % (number, prime))

if name == ‘main‘: main()

  1. > **重点**:**多线程和多进程的比较**。
  2. > 以下情况需要使用多线程:
  3. > 1. 程序需要维护许多共享的状态(尤其是可变状态),Python中的列表、字典、集合都是线程安全的,所以使用线程而不是进程维护共享状态的代价相对较小。
  4. > 2. 程序会花费大量时间在I/O操作上,没有太多并行计算的需求且不需占用太多的内存。
  5. >
  6. 以下情况需要使用多进程:
  7. > 1. 程序执行计算密集型任务(如:字节码操作、数据处理、科学计算)。
  8. > 2. 程序的输入可以并行的分成块,并且可以将运算结果合并。
  9. > 3. 程序在内存使用方面没有任何限制且不强依赖于I/O操作(如:读写文件、套接字等)。
  10. -
  11. 异步处理:从调度程序的任务队列中挑选任务,该调度程序以交叉的形式执行这些任务,我们并不能保证任务将以某种顺序去执行,因为执行顺序取决于队列中的一项任务是否愿意将CPU处理时间让位给另一项任务。异步任务通常通过多任务协作处理的方式来实现,由于执行时间和顺序的不确定,因此需要通过回调式编程或者`future`对象来获取任务执行的结果。Python 3通过`asyncio`模块和`await``async`关键字(在Python 3.7中正式被列为关键字)来支持异步处理。
  12. ```python
  13. """
  14. 异步I/O - async / await
  15. """
  16. import asyncio
  17. def num_generator(m, n):
  18. """指定范围的数字生成器"""
  19. yield from range(m, n + 1)
  20. async def prime_filter(m, n):
  21. """素数过滤器"""
  22. primes = []
  23. for i in num_generator(m, n):
  24. flag = True
  25. for j in range(2, int(i ** 0.5 + 1)):
  26. if i % j == 0:
  27. flag = False
  28. break
  29. if flag:
  30. print('Prime =>', i)
  31. primes.append(i)
  32. await asyncio.sleep(0.001)
  33. return tuple(primes)
  34. async def square_mapper(m, n):
  35. """平方映射器"""
  36. squares = []
  37. for i in num_generator(m, n):
  38. print('Square =>', i * i)
  39. squares.append(i * i)
  40. await asyncio.sleep(0.001)
  41. return squares
  42. def main():
  43. """主函数"""
  44. loop = asyncio.get_event_loop()
  45. future = asyncio.gather(prime_filter(2, 100), square_mapper(1, 100))
  46. future.add_done_callback(lambda x: print(x.result()))
  47. loop.run_until_complete(future)
  48. loop.close()
  49. if __name__ == '__main__':
  50. main()

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


Python中有一个名为aiohttp的三方库,它提供了异步的HTTP客户端和服务器,这个三方库可以跟asyncio模块一起工作,并提供了对Future对象的支持。Python 3.6中引入了asyncawait来定义异步执行的函数以及创建异步上下文,在Python 3.7中它们正式成为了关键字。下面的代码异步的从5个URL中获取页面并通过正则表达式的命名捕获组提取了网站的标题。

  1. import asyncio
  2. import re
  3. import aiohttp
  4. PATTERN = re.compile(r'\<title\>(?P<title>.*)\<\/title\>')
  5. async def fetch_page(session, url):
  6. async with session.get(url, ssl=False) as resp:
  7. return await resp.text()
  8. async def show_title(url):
  9. async with aiohttp.ClientSession() as session:
  10. html = await fetch_page(session, url)
  11. print(PATTERN.search(html).group('title'))
  12. def main():
  13. urls = ('https://www.python.org/',
  14. 'https://git-scm.com/',
  15. 'https://www.jd.com/',
  16. 'https://www.taobao.com/',
  17. 'https://www.douban.com/')
  18. loop = asyncio.get_event_loop()
  19. cos = [show_title(url) for url in urls]
  20. loop.run_until_complete(asyncio.wait(cos))
  21. loop.close()
  22. if __name__ == '__main__':
  23. main()

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

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


Python还有很多用于处理并行任务的三方库,例如:joblibPyMP等。实际开发中,要提升系统的可扩展性和并发性通常有垂直扩展(增加单个节点的处理能力)和水平扩展(将单个节点变成多个节点)两种做法。可以通过消息队列来实现应用程序的解耦合,消息队列相当于是多线程同步队列的扩展版本,不同机器上的应用程序相当于就是线程,而共享的分布式消息队列就是原来程序中的Queue。消息队列(面向消息的中间件)的最流行和最标准化的实现是AMQP(高级消息队列协议),AMQP源于金融行业,提供了排队、路由、可靠传输、安全等功能,最著名的实现包括:Apache的ActiveMQ、RabbitMQ等。
要实现任务的异步化,可以使用名为Celery的三方库。Celery是Python编写的分布式任务队列,它使用分布式消息进行工作,可以基于RabbitMQ或Redis来作为后端的消息代理。