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

版权声明:本文章为博主原创文章,未经博主允许不得转载,如有问题,欢迎留言交流指正 https://blog.csdn.net/finalkof1983/article/details/87943032

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

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:

def testFunctionAnnotations(a: int, b: str) ->str:
    return str(a) + b


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

 对应输出分别为:

{'a': <class 'int'>, 'b': <class 'str'>, 'return': <class 'str'>}
123test
123test

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

举例2:

def compile(source: "something compilable",
            filename: "where the compilable thing comes from",
            mode: "is this a single statement or a suite?"):

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

举例3:

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


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

对应输出分别为:

扫描二维码关注公众号,回复: 5663799 查看本文章
{'a': <class 'int'>, 'b': <class 'str'>, 'return': <class 'str'>}
123test
5default

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

举例4:

def testFunctionAnnotations(a: int = 5, b: int = 7) ->pow(2,3):
    z = lambda x, y:x*x  if x > y else y*y
    return z(a,b)


print(testFunctionAnnotations.__annotations__)
print(testFunctionAnnotations())

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

猜你喜欢

转载自blog.csdn.net/finalkof1983/article/details/87943032