預設引數的最佳實務
你的同事(顯然沒有上過這門課)寫了一個函式,用來替 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