Original link: https://chegva.com/5497.html
◎Knowledge points
-
Overview and use of partial functions
◎Script practice
"""Partial function""" """ When defining a function, you can set default values for the formal parameters to simplify the calling of the function. Only the formal parameters that do not match the default values need to be passed additional arguments. Partial functions can also simplify function calls. You can convert an existing function into a new function, and specify the first several positional arguments and keyword arguments during the conversion process. In this way, when the new function is called, the function before the conversion is still called internally, and only the remaining positional arguments and keyword arguments need to be passed when passing the actual parameters. The new function after transformation is called the partial function of the function before transformation. With the help of partial(func, *args, **kwargs) in the standard library module functools, You can convert an existing function into its partial function. """ from functools import partial def f(a, b = 5): print('a = ', a, 'b = ', b) f_new = partial(f, 2) f_new() # a = 2 b = 5 f_new(6) # a = 2 b = 6 f_new(b = 6) # a = 2 b = 6 # f_new(a = 3) # TypeError: f() got multiple values for argument 'a'
[zkqw]
def eval_sum(*args): s = 0 for n in args: s += n return s eval_sum_new = partial(eval_sum, 20, 30) print(eval_sum_new(1, 2, 3, 4, 5)) # 65
def f1(a, b = 5, *args, **kwargs): print('a =', a, 'b =', b, 'args =', args, 'kwargs =', kwargs) f1_new = partial(f1, 1, 3, 6, m = 8) f1_new(2, 4, n = 9) # a = 1 b = 3 args = (6, 2, 4) kwargs = {'m': 8, 'n': 9}
def f2(a, b = 5, *, c, **kwargs): print('a =', a, 'b =', b, 'c =', c, 'kwargs =', kwargs) f2_new = partial(f2, 1, m = 8) f2_new(3, c = 9) # a = 1 b = 3 c = 9 kwargs = {'m': 8}
◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/partial.py
[/zkqw]
This article is reprinted from: https://chegva.com/5497.html
This site is for inclusion only, and the copyright belongs to the original author.