Python3 function definition, arrow and colon [duplicate]

不羁岁月 提交于 2021-02-19 01:59:17

问题


I have found the following python function definition:

def reverseString(self, s: 'List[str]') -> 'None':

I don't quite understand 'List[str]' and -> 'None'.

I have found that the arrow is a function annotation but I couldn't find anything useful and understandable for List[str].

Is it just an annotation? or does it enforce that the type of parameter s must be a string array?


回答1:


It's just python type hinting, You can learn more in PEP 484




回答2:


This is an instance of python3 type hinting. The use of -> 'None' indicates that the function does not have a return statement.

List[str] is more interesting: The List part indicates it will return a list type, and its argument [str] indicates it is a parameterized type. In practice, python lists may contain any type of object, but in strongly-typed language a list is a homogeneous collection.

Using this hint both indicates to a caller of the function that s must contain only strings, thus avoiding any exceptions for whatever operation will be performed, and it also indicates to an intelligent IDE (e.g. PyCharm, VSCode) that the objects contained in the list have string instance methods for autocompletion indicators.

The python interpreter does not do anything with this information in terms type checking, however the mypy interpreter will typecheck your code.

For more information see PEP 484 and the typing module, which has also been backported to pre-3.5 python3 and 2.7.




回答3:


The list[str] does not really play a role as long as the function is always supplied with an s value when it is called. I tried the function with s: 'something different than list[str]' and it worked the same.


About the arrow issue, just try it:

def reverseString(self, s: 'List[str]') -> 'None':
    pass

Call:

output=reverseString('exampleinput1','exampleinput2')

Then check the output:

print(c)

None

type(output)

NoneType

More info about the arrow here.



来源:https://stackoverflow.com/questions/54551604/python3-function-definition-arrow-and-colon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!