current position：Home>Use of Python partial()
Use of Python partial()
2022-01-30 05:27:52 【waws520】
Today I'd like to introduce Python Partial functions in (functools.partial)
First , We need to simply understand the role of the lower partial function ： Like a decorator , It can extend the function function , But it is not equivalent to a decorator . The common application scenario is when we need to call a function frequently , Some of these parameters are known fixed values , Usually we can call this function more than once , But it looks like the code is redundant , The emergence of partial function is to solve this problem rarely . Take a very simple example , For example, I just want to know 100 What is the sum of any number , Usually our implementation is like this ：
# The first way ： def add(*args): return sum(args) print(add(1, 2, 3) + 100) print(add(5, 5, 5) + 100) # The second way def add(*args): # After adding the incoming values , Plus 100 return return sum(args) + 100 print(add(1, 2, 3)) # 106 print(add(5, 5, 5)) # 115 Copy code
See the code above , It seems quite simple , It's not very hard . But there are problems with both approaches ： The first one is ,100 This fixed value will return , The code always feels repetitive ; The second kind , When we want to modify 100 At this fixed value , We need to change add This method . Now let's take a look at parital How to achieve ：
from functools import partial def add(*args): return sum(args) add_100 = partial(add, 100) print(add_100(1, 2, 3)) # 106 add_101 = partial(add, 101) print(add_101(1, 2, 3)) # 107 Copy code
Is it simple ~
After knowing about the example of partial function , Let's look at the definition of partial function ：
class func = functools.partial(func, *args, **keywords) Copy code
We can see ,partial Must accept three parameters , From the previous example , We can also roughly know the role of these three parameters , A brief introduction ：
func: Functions that need to be extended , The function returned is actually a class func Function of *args: Position parameters that need to be fixed **kwargs: Keyword parameters that need to be fixed # If in the original function func Keyword in does not exist , Will expand , If there is , It will cover Copy code
Use a simple example code containing location parameters and keyword parameters to illustrate the usage ：
# It's also the code just summed , The difference is the keyword parameters added def add(*args, **kwargs): # Print position parameters for n in args: print(n) print("-"*20) # Print keyword parameters for k, v in kwargs.items(): print('%s:%s' % (k, v)) # Do not return for the time being , Just look at the parameter effect , understand partial usage # Normal call add(1, 2, 3, v1=10, v2=20) """ 1 2 3 -------------------- v1:10 v2:20 """ # partial add_partial = partial(add, 10, k1=10, k2=20) add_partial(1, 2, 3, k3=20) """ 10 1 2 3 -------------------- k1:10 k2:20 k3:20 """ add_partial(1, 2, 3, k1=20) """ 10 1 2 3 -------------------- k1:20 k2:20 """ Copy code
Last , Let's take a look at the explanation in the official documents , I believe with the previous Introduction , Look back at the official documents , It should be easier to understand , At the same time, it can also deepen our impression ：
functools.partial(func, *args, **keywords)
Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords. Roughly equivalent to:\
Simple translation : It returns a partial function object , This object and func equally , Can be called , At the same time, the location parameter can be specified when calling (args) and Key parameters ( *kwargs). If more positional parameters are provided, call , They will be attached to args in . If additional keyword parameters are provided , They will extend and overwrite the original keyword parameters . Its implementation is roughly equivalent to the following code ：
# Define a function , It takes three parameters def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords): newkeywords = keywords.copy() newkeywords.update(fkeywords) return func(*args, *fargs, **newkeywords) newfunc.func = func newfunc.args = args newfunc.keywords = keywords return newfunc Copy code
The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:\
Simple translation ：partial() Is used as “ frozen ” Some function parameters or keyword parameters , At the same time, an object with a new label will be generated ( That is, return a new function ). such as ,partial() It can be used to build a similar int() Function of , At the same time specified base Parameter is 2, The code is as follows ：
# The code is simple , I won't go on and on from functools import partial basetwo = partial(int, base=2) basetwo.__doc__ = 'Convert base 2 string to an int.' basetwo('10010') Copy code
Now let's see if the document is very clear .
author[waws520],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Python collects and monitors system data -- psutil
- Python chat room (Tkinter writing interface, streaming, socket to realize private chat, group chat, check chat records, Mysql to store data)
- Learning this Python library can reduce at least 100 lines of code
- leetcode 67. Add Binary（python）
- Regular re parameter replacement of Python 3 interface automation test framework
- V. pandas based on Python
- Only 15 lines of code is needed for face detection! (using Python and openCV)
- [Python crawler Sao operation] you can crawl Sirius cinema movies without paying
- leetcode 69. Sqrt(x)（python）
- Teach you to read the source code of Cpython (I)
guess what you like
Snowball learning started in the fourth quarter of Python. One needs three meals. I have a new understanding of Python functional programming, process-oriented, object-oriented and functional
leetcode 88. Merge Sorted Array（python）
Don't you know more about a python library before the end of 2021?
Python crawler web page parsing artifact XPath quick start teaching!!!
Use Python and OpenCV to watermark the image
String and related methods of Python data type introduction
Heapq module of Python module
Introduction to beautiful soup of Python crawler weapon, detailed explanation, actual combat summary!!!
Event loop of Python collaboration series
Django docking pin login system
- [recalling the 1970s] using Python to repair the wonderful memories of parents' generation, black-and-white photos become color photos
- You used to know Python advanced
- Pyinstaller package Python project
- 2021 IEEE programming language rankings: Python tops the list!
- Implementation of Python automatic test control
- Python advanced: [Baidu translation reverse] graphic and video teaching!!!
- Do you know the fuzzy semantics in Python syntax?
- [Python from introduction to mastery] (XXVII) learn more about pilot!
- Playing excel office automation with Python
- Some applications of heapq module of Python module
- Python and go languages are so popular, which is more suitable for you?
- Python practical skills task segmentation
- Python simulated Login, numpy module, python simulated epidemic spread
- Python opencv contour discovery function based on image edge extraction
- Application of Hoff circle detection in Python opencv
- Python reptile test ox knife (I)
- Day 1: learn the Django framework of Python development
- django -- minio_ S3 file storage service
- [algorithm learning] 02.03 Delete intermediate nodes (Java / C / C + + / Python / go)
- Similarities and differences of five pandas combinatorial functions
- Learning in Python + opencv -- extracting corners
- Python beginner's eighth day ()
- Necessary knowledge of Python: take you to learn regular expressions from zero
- Get your girlfriend's chat records with Python and solve the paranoia with one move
- My new book "Python 3 web crawler development practice (Second Edition)" has been recommended by the father of Python!
- From zero to familiarity, it will take you to master the use of Python len() function
- Python type hint type annotation guide
- leetcode 108. Convert Sorted Array to Binary Search Tree（python）
- For the geometric transformation of Python OpenCV image, let's first talk about the extraordinary resize function
- leetcode 701. Insert into a Binary Search Tree （python）
- For another 3 days, I sorted out 80 Python datetime examples, which must be collected!
- Python crawler actual combat | using multithreading to crawl lol HD Wallpaper
- Complete a python game in 28 minutes, "customer service play over the president card"
- The universal Python praise machine (commonly known as the brushing machine) in the whole network. Do you want to know the principle? After reading this article, you can write one yourself
- How does Python compare file differences between two paths
- Common OS operations for Python
- [Python data structure series] linear table - explanation of knowledge points + code implementation
- How Python parses web pages using BS4
- How do Python Network requests pass parameters
- Python core programming - decorator