I am new to coding business and the way I have learned defining functions in class do differ in some ways from this code (from Leetcode):
class Solution:
def search(self, nums: List[int], target: int) -> int:
If someone explain what does this definition of a function mean , more specifically what does colon mean , what is List[int] , and why there is a arrow , or is it like in mathematics ?
If necessary , this is using Python3
CodePudding user response:
This is type hinting in Python https://www.python.org/dev/peps/pep-0484/
This method definition says that the method is a part of a class, hence self keyword is provided and it takes as arguments nums which is a list of integers and a target which is a single int and the function returns a single integer ( -> int)
CodePudding user response:
Those are type hints. They specify what types each parameter should be, as well as the return type.
For your particular example, search() is an instance method that takes in two parameters:
nums, a list of integers, andtarget, an integer.
The function returns an int. The -> int is used to indicate that the return type is an integer.
Note that Python won't throw an error if these type hints aren't strictly followed (unlike Java or C , where a compilation error would occur). However, these hints can help detect potential typing bugs, as these types can be verified using a static typechecking library such as mypy.
CodePudding user response:
python is not a strongly typed language. so by default, python function definitions will not tell you what the return variable type or parameter variable types are. for ex:
def add(x, y):
return x y
but Leetcode is using type hinting: which means the variable type will be shown for the parameters and return value. for ex:
def add(x: int, y: int) -> int:
return x y
type hinting is used in probably most production/professional code by companies. when codebases get massive and there layers upon layers of abstraction, and Objects are wrapping around each other, type hinting makes it easier for developers to quickly determine what the method is returning and taking in as parameters.
