python函数声明(参数/返回值注释)和三个双引号用法

 

 1 # python的"""三个双引号两种用法:(1)多行注释  (2)定义多行字符串
 2 def f1(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
 3     print("函数注释", f1.__annotations__) # 函数注释 {'ham': 42, 'eggs': <class 'int'>, 'return': 'Nothing to see here'}
 4     print("参数值打印", ham, eggs)  # 参数值打印 www spam
 5     print(type(ham), type(eggs))  # <class 'str'> <class 'str'>
 6 
 7 f1("www") # 无类型校验提醒,第二个参数用默认值'spam'
 8 print('\n')
 9 f1("www", "hello") # 黄色波浪线类型校验 提醒“应为类型 'int',但实际为 'str' ”;第3行打印——gs': <class 'int'>, 'return': 'Nothing to see here'}
10 print('\n')
11 f1("www", 996)
12 print('\n')
13 
14 # max_len应该是一个大于0的整数,并且默认值为80。不过,这种写法 'int>0' 并不是Python标准的类型注解方式,它不会被Python解释器当作类型约束来执行,只是简单地将其视为一个注解字符串
15 # 更合理:def f2(text: str, max_len: int = 80) -> str:
16 # 正确的做法是使用类型注解,并且对于额外的约束(如必须大于0),通常应在函数体内部实现检查逻辑,如下
17 """
18 def f2(text: str, max_len: Annotated[int, "大于0的整数"] = 80) -> str:  # 它告诉阅读代码的人(以及某些静态类型检查器)有关max_len的意图
19     assert isinstance(max_len, int) and max_len > 0, "max_len 必须是一个大于0的整数"  # 但实际的约束条件(大于0)仍需通过assert语句或逻辑判断来手动实施
20     # 函数体...
21 """
22 
23 """
24 函数声明中,text:str
25 text 是参数 :冒号后面  str是参数的注释。
26 如果参数有默认值,还要给注释,如下写。
27 max_len:'int>0'=80
28 
29 ->str 是函数返回值的注释30 
31 这些注释信息都是函数的元信息,保存在f.__annotations__字典中、
32 
33 需要注意,python对注释信息和f.__annotations__的一致性,不做检查
34 不做检查,不做强制,不做验证!什么都不做。
35 """
36 def f2(text: str, max_len: 'int>0' = 80) -> str:
37     """这个是函数的帮助说明文档,help时会显示"""
38     print("函数注释", f2.__annotations__) # 函数注释 {'text': <class 'str'>, 'max_len': 'int>0', 'return': <class 'str'>}
39     print("参数值打印", text, max_len)  # 参数值打印 taobao new
40     print(type(text), type(max_len)) # <class 'str'> <class 'str'>
41 
42 f2("taobao", 'new')  # 参数值打印 taobao -1,前面的注释'int>0'

 

posted on 2024-06-18 15:24  gogoy  阅读(17)  评论(0编辑  收藏  举报

导航