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

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 能力有限,求各位大佬解答,谢谢。
Python函数头的问题有人了解吗?


10 回复

这玩意叫 annotation (注解),Python3 新加的特性。IDE 会根据注解信息来提供相应的方法。
代码里一般用不到~如果想玩玩的话,去看看 inspect 模块吧~

type hint, 标记参数 /返回的类型,帮助 IDE 或者其他工具更准确的帮你做类型检查 /重构。(像 python 这样的鸭子类型的语言工具没办法准确 refactoring)

google “Python 函数 冒号”

type hints 就是暗示 IDE 你方法参数和返回值的类型 如果使用的 python 版本比较低 也可以在注释里面通过
:type 和 :rtype 暗示 IDE

> name: str

你见过哪个 C 语言代码是这么写类型的?你说 Pascal 里的也就算了……

python cookbook3 上第 224 页

不是强制的 函数参数类型的注释

这个是为了方便别人读代码。毕竟动态语言没有强制规定参数类型。

dict 怎么注解想 ts 那样

回到顶部