Python 函数注释

  • Post author:
  • Post category:python




1. Google 风格

代码中常用的注释风格,也是我比较喜欢使用的。具体形式如下:

def test(param1, param2)
"""
This is a groups style docs.

Parameters:
  param1 - this is the first param
  param2 - this is a second param

Returns:
	This is a description of what is returned

Raises:
	KeyError - raises an exception
"""
	return param1 + param2

可以看到上述的包括了函数及其各个参数的具体用途,甚至包括了异常的类型。当然,我们也可进一步指定参数和返回值的类型。整个注释非常的清晰明了。



2. python 3.5 引入的类型提示

这种方法有点类似Java的函数定义,可以使用冒号与箭头来指定参数与返回值的类型。具体形式如下

def test(a:int, b:str) -> str:
    print(a, b)
    return 1000

if __name__ == '__main__':
    test('test', 'abc')


注解

Python 运行时不强制执行函数和变量类型注解,但这些注解可用于类型检查器、IDE、静态检查器等第三方工具。这种注释方式在阅读代码时是非常方便的,而且注释也是相当灵活的。也是最近阅读别人代码时发现的,后面先试用一段时间再说



3. Reference

  1. https://blog.csdn.net/sunt2018/article/details/83022493
  2. https://www.pythonf.cn/read/135762
  3. https://docs.python.org/zh-cn/3/library/typing.html



版权声明:本文为lollows原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。