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
Leigg
V2EX  ›  Python

Python 函数的高级写法?

  •  
  •   Leigg · 2018-08-27 16:45:54 +08:00 · 2316 次点击
    这是一个创建于 2040 天前的主题,其中的信息可能已经有所发展或是发生改变。

    看源码的时候,经常看到:

    def func(args) -> str: ...
    

    这种写法,问问大佬们这种写法什么意思,什么时候会用到?

    10 条回复    2018-08-29 01:17:59 +08:00
    WildCat
        1
    WildCat  
       2018-08-27 16:48:12 +08:00 via iPhone
    stevenshuang
        2
    stevenshuang  
       2018-08-27 16:48:21 +08:00 via iPhone
    返回类型
    lincanbin
        3
    lincanbin  
       2018-08-27 16:49:32 +08:00
    声明返回值类型,为了解决弱类型语言中某些操蛋的问题
    lincanbin
        4
    lincanbin  
       2018-08-27 16:51:01 +08:00
    Python 算是强类型语言,但是没有显式类型声明。
    例如 a + b,如果 a 跟 b 是字符串'1',那么结果是 11。
    如果 a 跟 b 是整数 1,那么结果是 2。
    huangzhe8263
        5
    huangzhe8263  
       2018-08-27 16:57:37 +08:00   ❤️ 1
    python 3.5 以上新加的, 专门用来规范实现类型标注的
    免得让接手的人或者半年后的自己想活剥了写代码的人的
    type hint

    特别是再加上 Pycharm 就更好用了
    lincanbin
        6
    lincanbin  
       2018-08-27 16:58:52 +08:00
    在没有显式类型声明的情况下,如果你的数据来源于其他接口,很可能你不知道或者不确定它是什么类型,那么你对这个数据的操作结果,也就不可预料。
    例如你计算用户完成若干个任务的返现,你从 json 接口 1 拿到{"a": "100"},从接口 2 拿到{"b": "100"}。
    原来你应该结算给用户 200 块的,现在你直接 a+b,好了,你给用户返现了 100100 块。

    如果你用:

    def add(a:int, b:int) -> int:
    return a + b

    这个问题就解决了
    cnrting
        7
    cnrting  
       2018-08-28 09:40:49 +08:00 via iPad
    @lincanbin "100100"不是 100100
    bmos
        8
    bmos  
       2018-08-28 14:31:11 +08:00
    @lincanbin 意思是 add('100','100'')返回 200 吗,我实验了一下好像没有效果。返回“ 100100"。py3.6
    frostming
        9
    frostming  
       2018-08-28 17:21:07 +08:00   ❤️ 1
    @lincanbin 类型标注并不会强制转换,所以就算你标了 int 传进来该是什么还是什么

    类型标注的意义只是为了让某些代码检查工具(如 mypy )做静态检查。
    Qzier
        10
    Qzier  
       2018-08-29 01:17:59 +08:00 via iPhone
    关键词 type hint
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3453 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 11:10 · PVG 19:10 · LAX 04:10 · JFK 07:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.