函数注释示例1

  1. def fun(name: str, age: \'是一个大于零的整数值\' = 52) -> \'返回值为真\':
  2. """
  3. 这个是函数的帮助说明文档,help时会显示
  4. 函数声明中,name:str
  5. name 是参数 :冒号后面 str是参数的注释。
  6. 如果参数有默认值,还要给注释,如下写。
  7. age:\'是一个大于零的整数值\'=52
  8. ->\'返回值为真\' 是函数返回值的注释。
  9. 这些注释信息都是函数的元信息,保存在f.__annotations__字典中、
  10. 需要注意,python对注释信息和f.__annotations__的一致性,不做检查
  11. 不做检查,不做强制,不做验证!什么都不做。
  12. :param name:
  13. :param age:
  14. :return:
  15. """
  16. return True
  17. print(fun.__annotations__)

打印结果如下:

  1. {\'name\': <class \'str\'>, \'age\': \'是一个大于零的整数值\', \'return\': \'返回值为真\'}

 

函数注释示例2:

  1. def func(ham: 42, eggs: int = \'spam\') -> "Nothing to see here":
  2. print("函数注释", func.__annotations__)
  3. print("参数值打印", ham, eggs)
  4. print(type(ham), type(eggs))
  5. func("www")

打印结果:

  1. 函数注释 {\'ham\': 42, \'eggs\': <class \'int\'>, \'return\': \'Nothing to see here\'}
  2. 参数值打印 www spam
  3. <class \'str\'> <class \'str\'>

解释说明:

注释的一般规则是参数名后跟一个冒号(:),然后再跟一个expression,这个expression可以是任何形式。 返回值的形式是 -> int,annotation可被保存为函数的attributes。

以上属于静态注释,还有一种方法叫做动态注释

动态注释的原理,就是在函数中或者装饰器中动态的增加 删除 更改 注释内容

  1. f.__annotations__ 是一个字典,可以使用字典的所有操作,这样就可以动态的更改注释了

 

  1. def foo():
  2. """ This is function foo"""

Google风格

  1. """
  2. This is a groups style docs.
  3. Parameters:
  4. param1 - this is the first param
  5. param2 - this is a second param
  6. Returns:
  7. This is a description of what is returned
  8. Raises:
  9. KeyError - raises an exception
  10. """

Rest风格

  1. """
  2. This is a reST style.
  3. :param param1: this is a first param
  4. :param param2: this is a second param
  5. :returns: this is a description of what is returned
  6. :raises keyError: raises an exception
  7. """

 

版权声明:本文为sui776265233原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/sui776265233/p/13360340.html