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
)
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
)
def function_name(arguments):
"""
函式用途的說明。
參數說明(若有)。
回傳值說明(若有)。
可能拋出的錯誤說明(若有)。
其他備註或使用範例(選用)。
"""
def function(arg_1, arg_2=42):
"""函式用途的說明。
"""
def function(arg_1, arg_2=42):
"""函式用途的說明。
Args:
arg_1 (str): 對 arg_1 的說明,必要時可換行。
arg_2 (int, optional): 若有預設值,請標註 optional。
"""
def function(arg_1, arg_2=42):
"""函式用途的說明。
Args:
arg_1 (str): 對 arg_1 的說明,必要時可換行。
arg_2 (int, optional): 若有預設值,請標註 optional。
Returns:
bool: 回傳值的可選說明。
續行不需縮排。
"""
def function(arg_1, arg_2=42):
"""函式用途的說明。
Args:
arg_1 (str): 對 arg_1 的說明,必要時可換行。
arg_2 (int, optional): 若有預設值,請標註 optional。
Returns:
bool: 回傳值的可選說明。
續行不需縮排。
Raises:
ValueError: 列出函式會刻意拋出的錯誤型別。
Notes:
See https://www.datacamp.com/community/tutorials/docstrings-python
for more info.
"""
def function(arg_1, arg_2=42):
"""
函式用途的說明。
Parameters
----------
arg_1 : expected type of arg_1
arg_1 的說明。
arg_2 : int, optional
若有預設值,請標註 optional。
Default=42。
Returns
-------
回傳值的型別
可包含回傳值說明。
若此函式為產生器,將「Returns」改為「Yields」。
"""
def the_answer(): """回傳生命、 宇宙與萬事萬物的答案。 Returns: int """ return 42print(the_answer.__doc__)
Return the answer to life,
the universe, and everything.
Returns:
int
import inspect
print(inspect.getdoc(the_answer))
Return the answer to life,
the universe, and everything.
Returns:
int
Python 函式寫作