干得好!

Python 函数编写

Shayne Miel

Software Architect @ Duo Security

第 1 章——最佳实践

  • 文档字符串(docstring)
  • DRY 与单一职责(Do One Thing)
  • 赋值传递(可变 vs 不可变)
Python 函数编写

第 2 章——上下文管理器

with my_context_manager() as value:
  # do something
@contextlib.contextmanager
def my_function():
  # this function can be used in a "with" statement now
Python 函数编写

第 3 章——装饰器

@my_decorator
def my_decorated_function():
  # do something
def my_decorator(func):
  def wrapper(*args, **kwargs):
    return func(*args, **kwargs)
  return wrapper
Python 函数编写

第 4 章——装饰器进阶

def my_decorator(func):
  @functools.wraps(func)
  def wrapper(*args, **kwargs):
    return func(*args, **kwargs)
  return wrapper
Python 函数编写

第 4 章——装饰器进阶

def decorator_that_takes_args(a, b, c):
  def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
      return func(*args, **kwargs)
    return wrapper
  return decorator
Python 函数编写

谢谢!

Python 函数编写

Preparing Video For Download...