Python 函数头的问题有人了解吗?

2018 年 5 月 20 日
 s04
def say_hi(name: str, age: int) -> str:
"""
Hi!
"""
# your code here
return "Hi. My name is %s and I'm %d years old" % (name, age)

if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert say_hi("Alex", 32) == "Hi. My name is Alex and I'm 32 years old", "First"
assert say_hi("Frank", 68) == "Hi. My name is Frank and I'm 68 years old", "Second"
print('Done. Time to Check.')
------------------------------------------------------------------------------
我不太明白 say_hi(name: str, age: int) -> str:这个函数头是什么含义。name: str, age: int 是不是 C 里边的类型声明?-> str:这块完全不理解。

google 能力有限,求各位大佬解答,谢谢。
4600 次点击
所在节点    Python
10 条回复
Arnie97
2018 年 5 月 20 日
threee333
2018 年 5 月 20 日
这玩意叫 annotation (注解),Python3 新加的特性。IDE 会根据注解信息来提供相应的方法。
代码里一般用不到~如果想玩玩的话,去看看 inspect 模块吧~
lxian2
2018 年 5 月 20 日
type hint, 标记参数 /返回的类型,帮助 IDE 或者其他工具更准确的帮你做类型检查 /重构。(像 python 这样的鸭子类型的语言工具没办法准确 refactoring)
mseasons
2018 年 5 月 20 日
google "Python 函数 冒号"
afpro
2018 年 5 月 20 日
type hints 就是暗示 IDE 你方法参数和返回值的类型 如果使用的 python 版本比较低 也可以在注释里面通过
:type 和 :rtype 暗示 IDE
msg7086
2018 年 5 月 20 日
> name: str

你见过哪个 C 语言代码是这么写类型的?你说 Pascal 里的也就算了……
RedFlag2233
2018 年 5 月 20 日
python cookbook3 上第 224 页
Kendall
2018 年 5 月 20 日
不是强制的 函数参数类型的注释
xiaoheijw
2018 年 5 月 20 日
这个是为了方便别人读代码。毕竟动态语言没有强制规定参数类型。
simple2025
2018 年 5 月 20 日
dict 怎么注解想 ts 那样

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/456216

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX