在 Python 中使用 `->`?
Use of `->` in Python?
谁能告诉我以下两个函数有什么区别?除了 ->
之外,它们看起来都非常相似。
foo1()
def foo1() -> None:
pass
foo2()
def foo2():
pass
当我以类似的方式称呼他们时。那么为什么要使用 -> None
呢?我知道 Python 的 None
的用法。
这叫做type hinting, and is only used to help make it easier for the programmer to understand the return and input types of a program, as well as allow for external linting and static analysis programs to work on Python. Here is the official RFC explaining why it exists。
Python 实际上并没有使用类型提示(因为 Python 是动态类型的 - 类型是在 运行时 确定的,而不是在编译时当源被实际解析时)并且可以安全地省略。
符合您的版本 2 的函数在任何情况下都非常好。
Python 3 内置了对 typing
模块类型提示的支持,而 Python 2.7 需要第三方 mypy
模块。
谁能告诉我以下两个函数有什么区别?除了 ->
之外,它们看起来都非常相似。
foo1()
def foo1() -> None:
pass
foo2()
def foo2():
pass
当我以类似的方式称呼他们时。那么为什么要使用 -> None
呢?我知道 Python 的 None
的用法。
这叫做type hinting, and is only used to help make it easier for the programmer to understand the return and input types of a program, as well as allow for external linting and static analysis programs to work on Python. Here is the official RFC explaining why it exists。
Python 实际上并没有使用类型提示(因为 Python 是动态类型的 - 类型是在 运行时 确定的,而不是在编译时当源被实际解析时)并且可以安全地省略。
符合您的版本 2 的函数在任何情况下都非常好。
Python 3 内置了对 typing
模块类型提示的支持,而 Python 2.7 需要第三方 mypy
模块。