V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
s04
V2EX  ›  Python

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

  •  
  •   s04 · 2018-05-20 00:16:34 +08:00 · 3554 次点击
    这是一个创建于 2140 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 能力有限,求各位大佬解答,谢谢。
    10 条回复    2018-05-20 14:38:29 +08:00
    Arnie97
        1
    Arnie97  
       2018-05-20 00:19:35 +08:00 via Android   ❤️ 1
    codergrowing
        2
    codergrowing  
       2018-05-20 00:25:54 +08:00 via Android   ❤️ 1
    这玩意叫 annotation (注解),Python3 新加的特性。IDE 会根据注解信息来提供相应的方法。
    代码里一般用不到~如果想玩玩的话,去看看 inspect 模块吧~
    lxian2
        3
    lxian2  
       2018-05-20 00:27:21 +08:00   ❤️ 1
    type hint, 标记参数 /返回的类型,帮助 IDE 或者其他工具更准确的帮你做类型检查 /重构。(像 python 这样的鸭子类型的语言工具没办法准确 refactoring)
    mseasons
        4
    mseasons  
       2018-05-20 01:04:11 +08:00
    google "Python 函数 冒号"
    afpro
        5
    afpro  
       2018-05-20 01:38:31 +08:00
    type hints 就是暗示 IDE 你方法参数和返回值的类型 如果使用的 python 版本比较低 也可以在注释里面通过
    :type 和 :rtype 暗示 IDE
    msg7086
        6
    msg7086  
       2018-05-20 07:36:51 +08:00
    > name: str

    你见过哪个 C 语言代码是这么写类型的?你说 Pascal 里的也就算了……
    RedFlag2233
        7
    RedFlag2233  
       2018-05-20 09:48:55 +08:00 via Android
    python cookbook3 上第 224 页
    Kendall
        8
    Kendall  
       2018-05-20 10:07:41 +08:00 via Android
    不是强制的 函数参数类型的注释
    xiaoheijw
        9
    xiaoheijw  
       2018-05-20 10:28:40 +08:00   ❤️ 1
    这个是为了方便别人读代码。毕竟动态语言没有强制规定参数类型。
    chenqh
        10
    chenqh  
       2018-05-20 14:38:29 +08:00 via Android
    dict 怎么注解想 ts 那样
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3749 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 05:05 · PVG 13:05 · LAX 22:05 · JFK 01:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.