进阶主题

Python 函数编写

Shayne Miel

Software Architect @ Duo Security

嵌套上下文

def copy(src, dst):
  """Copy the contents of one file to another.

  Args:
    src (str): File name of the file to be copied.
    dst (str): Where to write the new file.
  """

# 打开源文件并读取内容 with open(src) as f_src: contents = f_src.read() # 打开目标文件并写入内容 with open(dst, 'w') as f_dst: f_dst.write(contents)
Python 函数编写

嵌套上下文

with open('my_file.txt') as my_file:
  for line in my_file:
    # 执行操作
Python 函数编写

嵌套上下文

def copy(src, dst):
  """Copy the contents of one file to another.

  Args:
    src (str): File name of the file to be copied.
    dst (str): Where to write the new file.
  """

# 同时打开两个文件 with open(src) as f_src: with open(dst, 'w') as f_dst:
# 逐行读写 for line in f_src: f_dst.write(line)
Python 函数编写

错误处理

def get_printer(ip):
  p = connect_to_printer(ip)

  yield

  # 必须调用,否则他人将无法连接该打印机
  p.disconnect()
  print('disconnected from printer')

doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    printer.print_page(doc['txt'])
KeyError: 'txt'
Python 函数编写

错误处理

try:
  # 可能出错的代码
except:
  # 处理错误

finally: # 无论如何都会执行
Python 函数编写

错误处理

def get_printer(ip):
  p = connect_to_printer(ip)

  try:
    yield
  finally:
    p.disconnect()
    print('disconnected from printer')

doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt'])
disconnected from printer
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    printer.print_page(doc['txt'])
KeyError: 'txt'
Python 函数编写

上下文管理器模式

Open Close
Lock Release
Change Reset
Enter Exit
Start Stop
Setup Teardown
Connect Disconnect
1 改编自 Dave Brondsema 在 PyCon 2012 的演讲:https://youtu.be/cSbD5SKwak0?t=795
Python 函数编写

Passons à la pratique !

Python 函数编写

Preparing Video For Download...