使用 context manager

Python 函式寫作

Shayne Miel

Software Architect @ Duo Security

什麼是 context manager?

Context manager:

  • 建立情境
  • 執行你的程式碼
  • 移除情境
Python 函式寫作

外燴派對

空房間

Python 函式寫作

外燴派對

外燴佈置

Python 函式寫作

外燴派對

派對中

Python 函式寫作

外燴派對

外燴佈置

Python 函式寫作

外燴派對

空房間

Python 函式寫作

把外燴派對當情境類比

Context manager:

  • 建立情境
  • 執行你的程式碼
  • 移除情境

外燴團隊:

  • 佈置餐桌與餐飲
  • 讓你和朋友盡情開趴
  • 收拾並撤走餐桌
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 函式寫作

使用 context manager

with
Python 函式寫作

使用 context manager

with <context-manager>()
Python 函式寫作

使用 context manager

with <context-manager>(<args>)
Python 函式寫作

使用 context manager

with <context-manager>(<args>):
Python 函式寫作

使用 context manager

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

使用 context manager

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

# This code runs after the context is removed
Python 函式寫作

使用 context manager

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 函式寫作

一起來練習吧!

Python 函式寫作

Preparing Video For Download...