1. 为没有填充的(用pass代过)的fuction指定raiseError
当项目复杂时,我们可能会忘记没有完成的函数,调用时只执行空语句也不会有任何提示。为了防止这种情况,我们用ImplementError代替pass
# 直接pass,在项目变得复杂后可能会忽视没完成的功能
def display_information():
pass
#raise NotImplementedErroe
def display_information():
raise NotImplementedError("display_information function is not implemented")
2. 指定传入值和返回值的类型
这不仅能让我们在写代码的时候避免传进错误参数,也利于编辑器更好的进行补全提示
def display_info(info: dict[int, str]) -> dict[int,str]:
for key, value in info.items():
print(f"{key}: {value}")
return info
如图,指定类型后编辑器会有对应类型的提示,如果不指定就不会有
3. 为函数写说明文档
说明里记录函数的功能、传入参数、返回值,是给自己和他人参考的最直接的方式
def display_info (info: dict[int, str]) ->dict[int,str]:
"""
this function is used to display the information
:param info:a dictionary with integer keys and string values
:return:dict[int,str]
"""