做得好!

Python 函式寫作

Shayne Miel

Software Architect @ Duo Security

第 1 章-最佳實務

  • Docstring 文件字串
  • DRY 與單一職責
  • 指派傳遞(可變 vs 不可變)
Python 函式寫作

第 2 章-情境管理器(Context Manager)

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 章-裝飾器(Decorator)

@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...