日志(Logging)

日志是装饰器运用的另一个亮点。这是个例子:

  1. from functools import wraps
  2. def logit(func):
  3. @wraps(func)
  4. def with_logging(*args,**kwargs):
  5. print(func.__name__ +" was called")
  6. return func(*args,**kwargs)
  7. return with_logging
  8. @logit
  9. def addition_func(x):
  10. """Do some math."""
  11. return x + x
  12. result = addition_func(4)
  13. # Output: addition_func was called

我敢肯定你已经在思考装饰器的一个其他聪明用法了。