python的新特性函数注释(定义函数时使用“:”及“ ->”符号)

刷题的时候发现有的题目函数定义格式类型是这样的:

def lengthOfLongestSubstring(self, s: str) -> int:

这种定义方式完全没明白啥意思,于是经过一番查找,大体意思如下:

这是python3的新特性,简单理解为s:str中的s还是你要传的形参这个没有变,str为该形参的注释,意思是告诉你传入的s应该是个字符串,当然这里重点理解一下注释二字,也就是说python仍然是动态赋值类型语言,这里虽然告诉你s应该是字符串,但是你传一个int进去,你的代码也是可以正常跑的(前提是代码内部能正常处理该类型),只不过如果你使用的IDE是pycharm这种的,会产生一些警告,而且这样的话注释也变的没有意义了。而后面的-> int是return返回值的类型注释,告诉你这个函数返回的是一个int类型,当然和参数注释一样,仅仅是注释。(官方文档PEP 3107 -- Function Annotations)

 

举例1:

 
  1. def testFunctionAnnotations(a: int, b: str) ->str:

  2. return str(a) + b

  3.  
  4.  
  5. print(testFunctionAnnotations.__annotations__)

  6. print(testFunctionAnnotations(123, "test"))

  7. print(testFunctionAnnotations("123", "test"))

 对应输出分别为:

 
  1. {'a': <class 'int'>, 'b': <class 'str'>, 'return': <class 'str'>}

  2. 123test

  3. 123test

可以看出即使你对a使用str类型,也不会影响你的程序的运行。 

举例2:

 
  1. def compile(source: "something compilable",

  2. filename: "where the compilable thing comes from",

  3. mode: "is this a single statement or a suite?"):

官方的示例,意在说明注释可以写很多很多,只要你不嫌长...

举例3:

 
  1. def testFunctionAnnotations(a: int = 5, b: str = "default") ->str:

  2. return str(a) + b

  3.  
  4.  
  5. print(testFunctionAnnotations.__annotations__)

  6. print(testFunctionAnnotations(123, "test"))

  7. print(testFunctionAnnotations())

对应输出分别为:

 
  1. {'a': <class 'int'>, 'b': <class 'str'>, 'return': <class 'str'>}

  2. 123test

  3. 5default

注释也不影响你使用默认参数,注意一下写法就是了

举例4:

 
  1. def testFunctionAnnotations(a: int = 5, b: int = 7) ->pow(2,3):

  2. z = lambda x, y:x*x if x > y else y*y

  3. return z(a,b)

  4.  
  5.  
  6. print(testFunctionAnnotations.__annotations__)

  7. print(testFunctionAnnotations())

注释部分是一个表达式,既可以是上面的字符串也可以是相关函数的示例,且注释函数的参数需要是常数,如pow(2,3)是可以的,如果写成pow(a, b)、pow(x, y)会报参数未定义。

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值