真实案例

Python 函数编写

Shayne Miel

Software Architect @ Duo Security

计时函数

import time

def timer(func):
  """一个装饰器,用于打印函数运行所用时间。

  Args:
    func (callable): 被装饰的函数。

  Returns:
    callable: 装饰后的函数。
  """
Python 函数编写
import time

def timer(func):
  """一个装饰器,用于打印函数运行所用时间。"""

# 定义要返回的包装函数。 def wrapper(*args, **kwargs):
# 当调用 wrapper() 时,获取当前时间。 t_start = time.time()
# 调用被装饰函数并存储结果。 result = func(*args, **kwargs)
# 计算总耗时并打印。 t_total = time.time() - t_start print('{} took {}s'.format(func.__name__, t_total))
return result
return wrapper
Python 函数编写

使用 timer()

@timer
def sleep_n_seconds(n):
  time.sleep(n)
sleep_n_seconds(5)
sleep_n_seconds took 5.0050950050354s
sleep_n_seconds(10)
sleep_n_seconds took 10.010067701339722s
Python 函数编写
def memoize(func):
  """缓存被装饰函数的结果以便快速查找
  """

# 用字典按参数映射到结果 cache = {}
# 定义要返回的包装函数。 def wrapper(*args, **kwargs): # 为 'kwargs' 定义可哈希的键。 kwargs_key = tuple(sorted(kwargs.items()))
# 如果这些参数是首次出现, if (args, kwargs_key) not in cache:
# 调用 func() 并存储结果。 cache[(args, kwargs_key)] = func(*args, **kwargs)
return cache[(args, kwargs_key)]
return wrapper
Python 函数编写
@memoize
def slow_function(a, b):
  print('Sleeping...')
  time.sleep(5)
  return a + b
slow_function(3, 4)
Sleeping...

7
slow_function(3, 4)
7
Python 函数编写

何时使用装饰器

  • 为多个函数添加通用行为
@timer
def foo():
  # do some computation

@timer
def bar():
  # do some other computation

@timer
def baz():
  # do something else
Python 函数编写

开始练习!

Python 函数编写

Preparing Video For Download...