Python函数声明“def twoSum(self, nums: List[int], target: int) -> List[int]:“的解释

2022/6/23 5:19:45

本文主要是介绍Python函数声明“def twoSum(self, nums: List[int], target: int) -> List[int]:“的解释,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

问题?

对函数twoSum进行定义时,出现了“List[int]、int、->List[int]”类似于“注释”的语法,如下代码。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

是什么?

由于 Python 的 2.x 系列缺乏注释函数参数和返回值的标准方法,从Python 3.0后,引入了给函数添加任意元数据注释的语法。

那么这些函数注释(Function annotations)是什么呢?参考官方文档:PEP 3107 – Function Annotations 

  • 完全可选择的,为函数的参数和返回值做注释
  • 仅仅在编译时,函数注释将任意python表达式与函数各个部分联系起来的一种方式。所以python本身不对函数注释赋予明确的意义,只是可以由第三方库来使用注释,如下代码;因此有第三方库对参数和返回值进行类型控制(官网举了例子,但是没看懂,可能是可以发展的一个方向)
  • 因此官方并没有对函数注释引入标准语义,交给第三方库处理。
def compile(source: "something compilable",
            filename: "where the compilable thing comes from",
            mode: "is this a single statement or a suite?"):
    ...

怎么用?

1. 参数

def foo(a: expression, b: expression = 5):

2. 返回值

def sum() -> expression:

特点?

1.__annotations__ 

相较于日常的注释,我们可以用__annotations__ 提取出相关的注释值。仅当为函数的返回值提供注释时,此键才存在。

def kinetic_energy(m:'in KG', v:'in M/S')->'Joules': 
    return 1/2*m*v**2
 

>>> kinetic_energy.__annotations__
{'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}

(也没有想到有很好的应用场景)

2. typing 第三方类型检查工具, python 3.5之后版本可以使用,包括List, AnyUnionCallableTypeVar, and Generic等类型

参考:typing — Support for type hints  和  PEP 483 – The Theory of Type Hints

from typing import List  #  type support for annotations List

class Solution(object):
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

但是,进行测试如下。只是为了说明参数和返回值的数据类型,给阅读提供参考,实际上程序并不检查是否是相符。

def fun(x: int) -> str:
    return [x]


>>> fun('asd')
['asd']

 

参考文章:

  • https://blog.csdn.net/allway2/article/details/116101988
  • https://blog.csdn.net/weixin_45798684/article/details/106037680
  • https://stackoverflow.com/questions/14379753/what-does-mean-in-python-function-definitions
  • https://stackoverflow.com/questions/14379753/what-does-mean-in-python-function-definitions

 



这篇关于Python函数声明“def twoSum(self, nums: List[int], target: int) -> List[int]:“的解释的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程