Python函数声明“def twoSum(self, nums: List[int], target: int) -> List[int]:“的解释
Posted on 2022-06-23 02:29 Xxiscoming 阅读(3399) 评论(0) 编辑 收藏 举报问题?
对函数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, Any
, Union
, Callable
, TypeVar
, 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步