- 函数命名:函数名字要见名知意,看名字就知道函数做什么。
- docstring(文档字符串):全称
documentation string,专门用来给函数写说明文档。 - 写在
def函数定义的下一行,使用三引号"""..."""包裹,可以多行文本。 - 注意:文档字符串本身不受缩进约束,但是后面真正的业务代码,必须保持正常缩进。
- docstring不是注释,它是字符串对象,可以代码里读取,
help(函数名)可以直接查看这份说明。
示例代码
def in_fridge():
"""这个一个查找冰箱里面某种食品的数量"""
try:
count = fridge[wanted_food]
except KeyError:
count = 0
return countCode language: PHP (php)
英文原版docstring版本:
def in_fridge():
"""This is a function to see if the fridge has a food.
fridge has to be a dictionary defined outside of the function.
the food to be searched for is in the string wanted_food"""
try:
count = fridge[wanted_food]
except KeyError:
count = 0
return countCode language: PHP (php)
查看文档字符串两种方式
# 方式1:help 查看函数帮助
help(in_fridge)
# 方式2:读取函数 __doc__ 属性
print(in_fridge.__doc__)Code language: PHP (php)
改进版(带参数和规范docstring)
原课件函数依赖全局变量,实际项目建议传入参数,文档写明参数、返回值含义
def in_fridge(fridge_dict, wanted_food):
"""检查冰箱字典中指定食物的数量
Args:
fridge_dict (dict): 冰箱存储食物的字典
wanted_food (str): 需要查找的食物名称
Returns:
any: 找到返回对应value,找不到返回0
"""
try:
count = fridge_dict[wanted_food]
except KeyError:
count = 0
return count
fridge = {"milk":"这是牛奶", "egg":"这是鸡蛋"}
print(in_fridge(fridge, "milk"))
# 查看文档
help(in_fridge)Code language: PHP (php)
重点区分 docstring 和普通注释
#:普通注释,程序运行直接忽略,外部无法代码读取。"""..."""docstring:函数/类下第一行三引号字符串,属于对象属性,help()可以读取展示给使用者。
运行help(in_fridge)输出效果:
Help on function in_fridge in module __main__:
in_fridge(fridge_dict, wanted_food)
检查冰箱字典中指定食物的数量
Args:
fridge_dict (dict): 冰箱存储食物的字典
wanted_food (str): 需要查找的食物名称
Returns:
any: 找到返回对应value,找不到返回0Code language: JavaScript (javascript)