iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python函数注释,参数后面加冒号:,
  • 883
分享到

python函数注释,参数后面加冒号:,

冒号注释函数 2023-01-31 01:01:42 883人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

python的函数注释: def f(text:str,max_len:'int>0'=80) ->str: """这个是函数的帮助说明文档,help时会显示""" return True """ 函数声明中

python的函数注释:

def f(text:str,max_len:'int>0'=80) ->str:
	"""这个是函数的帮助说明文档,help时会显示"""
    return True
"""
函数声明中,text:str
text 是参数 :冒号后面  str是参数的注释。
如果参数有默认值,还要给注释,如下写。
max_len:'int>0'=80

->str 是函数返回值的注释。

这些注释信息都是函数的元信息,保存在f.__annotations__字典中、

需要注意,Python对注释信息和f.__annotations__的一致性,不做检查
不做检查,不做强制,不做验证!什么都不做。
"""

函数注释示例:

def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
    print("函数注释", f.__annotations__)
    print("参数值打印", ham, eggs)
    print(type(ham),type(eggs))

f("www")

返回信息:

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

解释说明:

注释的一般规则是参数名后跟一个冒号(:),然后再跟一个expression,这个expression可以是任何形式。

返回值的形式是 -> int,annotation可被保存为函数的attributes。

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

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

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

大多数情况,我使用的是一下方法,进行注释说明

def foo():
  """ This is function foo"""

Google风格
"""
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
"""

Rest风格
"""
This is a reST style.

:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""

--结束END--

本文标题: python函数注释,参数后面加冒号:,

本文链接: https://www.lsjlt.com/news/184982.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作