文档字符串

Python 函数编写

Shayne Miel

Software Architect @ Duo Security

复杂函数

def split_and_stack(df, new_names):
  half = int(len(df.columns) / 2)
  left = df.iloc[:, :half]
  right = df.iloc[:, half:]
  return pd.DataFrame(
    data=np.vstack([left.values, right.values]),
    columns=new_names
  )
Python 函数编写
def split_and_stack(df, new_names):
  """将 DataFrame 的列分成两半后垂直堆叠,
  返回列名为 `new_names` 的新 DataFrame。
  Args:

    df (DataFrame): 要拆分的 DataFrame。
    new_names (iterable of str): 新 DataFrame 的列名。
  Returns:

    DataFrame
  """
  half = int(len(df.columns) / 2)
  left = df.iloc[:, :half]
  right = df.iloc[:, half:]
  return pd.DataFrame(
    data=np.vstack([left.values, right.values]),
    columns=new_names
  )
Python 函数编写

文档字符串的结构

def function_name(arguments):
  """
  函数的作用描述。

  参数的描述(如有)。

  返回值的描述(如有)。

  抛出错误的描述(如有)。

  可选的补充说明或用法示例。
  """
Python 函数编写

文档字符串格式

  • Google 风格
  • Numpydoc
  • reStructuredText
  • EpyText
Python 函数编写

Google 风格——描述

def function(arg_1, arg_2=42):
  """函数的作用描述。
  """
Python 函数编写

Google 风格——参数

def function(arg_1, arg_2=42):
  """函数的作用描述。

  Args:
    arg_1 (str): 对 arg_1 的描述,必要时可换行。
    arg_2 (int, optional): 当参数有默认值时写 optional。
  """
Python 函数编写

Google 风格——返回值

def function(arg_1, arg_2=42):
  """函数的作用描述。

  Args:
    arg_1 (str): 对 arg_1 的描述,必要时可换行。
    arg_2 (int, optional): 当参数有默认值时写 optional。
  Returns:
    bool: 返回值的可选描述

    额外行不缩进。
  """
Python 函数编写
def function(arg_1, arg_2=42):
  """函数的作用描述。

  Args:
    arg_1 (str): 对 arg_1 的描述,必要时可换行。
    arg_2 (int, optional): 当参数有默认值时写 optional。
  Returns:
    bool: 返回值的可选描述

    额外行不缩进。
  Raises:
    ValueError: 列出函数有意抛出的错误类型。

  Notes:
    参见 https://www.datacamp.com/community/tutorials/docstrings-python
    了解更多信息。  

  """
Python 函数编写

Numpydoc

def function(arg_1, arg_2=42):
  """
  函数的作用描述。

  Parameters
  ----------
  arg_1 : arg_1 的期望类型
    arg_1 的描述。
  arg_2 : int, optional
    当参数有默认值时写 optional。
    Default=42。

  Returns
  -------
  返回值的类型
    可包含对返回值的描述。
    若为生成器,将 "Returns" 改为 "Yields"。
  """
Python 函数编写

获取文档字符串

def the_answer():
  """返回生命、
  宇宙以及万物的答案。

  Returns:
    int
  """
  return 42

print(the_answer.__doc__)
返回生命、
  宇宙以及万物的答案。

  Returns:
    int
import inspect
print(inspect.getdoc(the_answer))
返回生命、
宇宙以及万物的答案。

Returns:
  int
Python 函数编写

Passons à la pratique !

Python 函数编写

Preparing Video For Download...