Abstract: The core design principle of python is simplicity - guided by this principle, lambda expressions and partial functions were born: both make function calls concise. This article mainly introduces you to the application of partial functions.
Why use partial functions
If we define a function, say add(one,two,three,four) to add four numbers, there are many functions in the upper layer that need to call this function. In these calls, 80% of the passed parameters are one=1, two=20. If we enter the same parameters every time, it is tedious and wasteful. Of course, we can solve this problem by default parameters; but if In addition, we also need the parameters to be one=2, two=10? Therefore, we need a function that can convert a function of any number of parameters into a function object with the remaining parameters.
Through the above, we roughly understand what a partial function is: simply put, a partial function is the realization of a function with fixed parameters, so we need:
1) Name the partial function
2) Passing fixed parameters
from functools import partial def add(a,b): return a+b p1 = partial(add, 100) p2 = partial(add, 90) print('p1=', p1(99)) print('p2=', p2(30)) ''' result: p1=199 p2=120 '''
Use partial functions
Combine getattr reflection
import functools class RequestContext(object): def __init__(self): self.request = "xxxxx" self.session = "iusdkfjlskdf" obj = RequestContext() # obj.request # obj.session def get_data(name): return getattr(obj,name) request_proxy = functools.partial(get_data,'request') session_proxy = functools.partial(get_data,'session') request = request_proxy() print(request) session = session_proxy() print(session)
Result:
"xxxxx"
"iusdkfjlskdf"