Smooth python and cookbook learning notes (9), pythoncookbook
1. Reduce the number of parameters of callable objects and use functools. partial to freeze Parameters
Use functools. partial () to fix one or more values to reduce the call parameters.
>>> Def spam (a, B, c, d ):... print (a, B, c, d)...> from functools import partial >>> s1 = partial (spam, 1) # set the value of a to 1 >>> s1 (2, 3, 4) 1 2 3 4> s1 (4, 2, 7) 1 4 2 7> s2 = partial (spam, d = 42) # Set the value of d to 42 >>> s2 (1, 2, 3) 1 2 3 42 >>> s2 (3, 2, 3) 3 2 3 42 >>> s3 = partial (spam, 1, 2, d = 42) # a = 1, B = 2, d = 42 >>> s3 (2) 1 2 2 42> s3 (28)
2. Add metadata to function parameters
Each parameter in the function declaration can be followed by an annotation expression. If the parameter has a default value, the annotation is placed between the parameter name and the = sign. If you want to annotate the return value, add-> and an expression between) and: at the end of the function declaration.
The expression can be of any type. The most common types of annotations are classes (such as str or int) and strings (such as 'int> 0 ').
>>> Def add (x: int, y: int)-> int :... return x + y... >>> add (2, 4) 6 >>> help (add) Help on function add in module _ main __: add (x: int, y: int) -> int >>> add. _ annotations __{ 'X': <class 'int'>, 'y': <class 'int'>, 'Return ': <class 'int' >}# function annotations are only stored in the annotations attribute of the function.