推荐学习书目
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 · Aug 27, 2018 · 3180 views
    This topic created in 2848 days ago, the information mentioned may be changed or developed.

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

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

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

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

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

    如果你用:

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

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

    类型标注的意义只是为了让某些代码检查工具(如 mypy )做静态检查。
    Qzier
        10
    Qzier  
       Aug 29, 2018 via iPhone
    关键词 type hint
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2529 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 15:47 · PVG 23:47 · LAX 08:47 · JFK 11:47
    ♥ Do have faith in what you're doing.