1. Learn
  2. /
  3. 课程
  4. /
  5. Python 函数编写

Connected

道练习

默认参数的最佳实践

您的一位同事(显然没有学过这门课)写了一个函数,用来给 pandas 的 DataFrame 添加一列。不幸的是,他把可变变量用作了默认参数值!请向他展示更好的写法,避免出现意外行为。

def add_column(values, df=pandas.DataFrame()):
  """Add a column of `values` to a DataFrame `df`.
  The column will be named "col_<n>" where "n" is
  the numerical index of the column.

  Args:
    values (iterable): The values of the new column
    df (DataFrame, optional): The DataFrame to update.
      If no DataFrame is passed, one is created by default.

  Returns:
    DataFrame
  """
  df['col_{}'.format(len(df.columns))] = values
  return df

说明

100 XP
  • 将 df 的默认值改为不可变值,以符合最佳实践。
  • 更新函数代码:当调用方未传入 DataFrame 时,应创建一个新的 DataFrame。