使用上下文管理器

Python 函数编写

Shayne Miel

Software Architect @ Duo Security

什么是上下文管理器?

上下文管理器:

  • 建立上下文
  • 运行代码
  • 移除上下文
Python 函数编写

外烩派对

空房间

Python 函数编写

外烩派对

外烩房间

Python 函数编写

外烩派对

派对房间

Python 函数编写

外烩派对

外烩房间

Python 函数编写

外烩派对

空房间

Python 函数编写

将外烩派对比作上下文

上下文管理器:

  • 建立上下文
  • 运行代码
  • 移除上下文

餐饮服务:

  • 摆放餐桌与饮品
  • 让你们开派对
  • 清理并撤走餐桌
Python 函数编写

真实示例

with open('my_file.txt') as my_file:
  text = my_file.read()
  length = len(text)

print('The file is {} characters long'.format(length))

open() 做三件事:

  • 通过打开文件建立上下文
  • 允许你在该文件上运行任意代码
  • 通过关闭文件移除上下文
Python 函数编写

使用上下文管理器

with
Python 函数编写

使用上下文管理器

with <context-manager>()
Python 函数编写

使用上下文管理器

with <context-manager>(<args>)
Python 函数编写

使用上下文管理器

with <context-manager>(<args>):
Python 函数编写

使用上下文管理器

with <context-manager>(<args>):
  # Run your code here
  # This code is running "inside the context"
Python 函数编写

使用上下文管理器

with <context-manager>(<args>):
  # Run your code here
  # This code is running "inside the context"

# This code runs after the context is removed
Python 函数编写

使用上下文管理器

with <context-manager>(<args>) as <variable-name>:
  # Run your code here
  # This code is running "inside the context"

# This code runs after the context is removed
with open('my_file.txt') as my_file:
  text = my_file.read()
  length = len(text)

print('The file is {} characters long'.format(length))
Python 函数编写

Passons à la pratique !

Python 函数编写

Preparing Video For Download...