【问题标题】:Is it possible to have static type declarations for function input arguments in Python3.7? [duplicate]Python3.7 中是否可以对函数输入参数进行静态类型声明? [复制]
【发布时间】:2019-09-21 01:13:46
【问题描述】:

这是我在 leetcode.com 上的 Python3 代码框架中看到的语法。注意函数输入参数的类型声明(或者至少我认为它们是类型声明,以前从未见过)。 nums 必须是intList,并且s 必须是int

class Solution:
    def findTargetSumWays(self, nums: List[int], S: int) -> int:
        pass

如果我在 leetcode.com 的环境中运行该函数,它会退出且不会出错。但是,如果我在自己的 Python 3.7.3 环境中运行相同的代码,则会收到 NameError。

def findTargetSumWays(self, nums: List[int], S: int) -> int: NameError: name 'List' is not defined

怎么了? leetcode.com 上的语法是真正的 Python 吗?

【问题讨论】:

  • 您可以从typing 模块导入List
  • 技术术语是函数注释,其中一种用途(也是唯一官方支持的用途)用于类型提示。

标签: python python-3.x types nameerror


【解决方案1】:

是的,这是真正的语法,我相信从 3.7 开始正式使用。

此静态类型中使用的List 是从typing 模块导入的。

您可以在PEP-484: Type Hintstyping module docs 中了解更多信息。

【讨论】:

  • 啊! leetcode.com 上的隐形导入让我上当了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 1970-01-01
  • 2020-03-05
  • 2014-03-02
  • 1970-01-01
  • 2021-08-23
相关资源
最近更新 更多