Python 写函数时的一些好习惯 为函数指定传入参数、返回值类型

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]
    """

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值