默认参数的最佳实践
您的一位同事(显然没有学过这门课)写了一个函数,用来给 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
本练习是课程的一部分
Python 函数编写
练习说明
- 将
df的默认值改为不可变值,以符合最佳实践。 - 更新函数代码:当调用方未传入 DataFrame 时,应创建一个新的 DataFrame。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Use an immutable variable for the default argument
def better_add_column(values, df=____):
"""Add a column of `values` to a DataFrame `df`.
The column will be named "col_" 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
"""
# Update the function to create a default DataFrame
if ____ is ____:
df = pandas.DataFrame()
df['col_{}'.format(len(df.columns))] = values
return df