装饰器与元数据

Python 函数编写

Shayne Miel

Software Architect @ Duo Security

def sleep_n_seconds(n=10):
  """暂停执行 n 秒。

  参数:
    n (int):暂停的秒数。
  """
  time.sleep(n)

print(sleep_n_seconds.__doc__)
暂停执行 n 秒。

  参数:
    n (int):暂停的秒数。
Python 函数编写
def sleep_n_seconds(n=10):
  """暂停执行 n 秒。

  参数:
    n (int):暂停的秒数。
  """
  time.sleep(n)

print(sleep_n_seconds.__name__)
sleep_n_seconds
print(sleep_n_seconds.__defaults__)
(10,)
Python 函数编写
@timer
def sleep_n_seconds(n=10):
  """暂停执行 n 秒。

  参数:
    n (int):暂停的秒数。
  """
  time.sleep(n)

print(sleep_n_seconds.__doc__)


print(sleep_n_seconds.__name__)
wrapper
Python 函数编写

timer 装饰器

def timer(func):
  """打印函数运行耗时的装饰器。"""

  def wrapper(*args, **kwargs):
    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 函数编写
from functools import wraps

def timer(func): """打印函数运行耗时的装饰器。""" @wraps(func) def wrapper(*args, **kwargs):
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
def sleep_n_seconds(n=10):
  """暂停执行 n 秒。

  参数:
    n (int):暂停的秒数。
  """
  time.sleep(n)

print(sleep_n_seconds.__doc__)
暂停执行 n 秒。

  参数:
    n (int):暂停的秒数。
Python 函数编写
@timer
def sleep_n_seconds(n=10):
  """暂停执行 n 秒。

  参数:
    n (int):暂停的秒数。
  """
  time.sleep(n)

print(sleep_n_seconds.__name__)
sleep_n_seconds
Python 函数编写

访问原始函数

@timer
def sleep_n_seconds(n=10):
  """暂停执行 n 秒。

  参数:
    n (int):暂停的秒数。
  """
  time.sleep(n)

sleep_n_seconds.__wrapped__
<function sleep_n_seconds at 0x7f52cab44ae8>
Python 函数编写

Passons à la pratique !

Python 函数编写

Preparing Video For Download...