การใช้ context manager

การเขียนฟังก์ชันใน Python

Shayne Miel

Software Architect @ Duo Security

context manager คืออะไร?

context manager:

  • ตั้งค่า context
  • รันโค้ดของคุณ
  • ลบ context ออก
การเขียนฟังก์ชันใน Python

งานเลี้ยงพร้อมบริการจัดเลี้ยง

ห้องว่างเปล่า

การเขียนฟังก์ชันใน Python

งานเลี้ยงพร้อมบริการจัดเลี้ยง

ห้องจัดเลี้ยง

การเขียนฟังก์ชันใน Python

งานเลี้ยงพร้อมบริการจัดเลี้ยง

ห้องงานปาร์ตี้

การเขียนฟังก์ชันใน Python

งานเลี้ยงพร้อมบริการจัดเลี้ยง

ห้องจัดเลี้ยง

การเขียนฟังก์ชันใน Python

งานเลี้ยงพร้อมบริการจัดเลี้ยง

ห้องว่างเปล่า

การเขียนฟังก์ชันใน Python

งานเลี้ยงในฐานะ context

Context manager:

  • ตั้งค่า context
  • รันโค้ดของคุณ
  • ลบ context ออก

ทีมจัดเลี้ยง:

  • จัดโต๊ะอาหารและเครื่องดื่ม
  • ให้คุณและเพื่อนๆ เพลิดเพลินกับงานปาร์ตี้
  • เก็บและนำโต๊ะออกหลังงาน
การเขียนฟังก์ชันใน 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() ทำสามสิ่ง:

  • ตั้งค่า context โดยเปิดไฟล์
  • ให้รันโค้ดใดก็ได้กับไฟล์นั้น
  • ลบ context โดยปิดไฟล์
การเขียนฟังก์ชันใน 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...