Summary of using Python's functools module
This article brings you relevant knowledge about Python. It mainly introduces the use and description of Python's functools module. It has a good reference value. Let's take a look at it together. I hope it will be helpful to everyone. helpful.
[Related recommendations: Python3 video tutorial]
partial
is used to create a partial function, The default parameters wrap a callable object, and the returned result is also a callable object.
Partial functions can fix some parameters of the original function, making it easier to call.
from functools import partial int2 = partial(int, base=8) print(int2('123')) # 83
update_wrapper
Functions wrapped using partial do not have __name__ and __doc__ attributes.
update_wrapper Function: Copy the __name__ and other attributes of the wrapped function to the new function.
from functools import update_wrapper def wrap2(func): def inner(*args): return func(*args) return update_wrapper(inner, func) @wrap2 def demo(): print('hello world') print(demo.__name__) # demo
wraps
The warps function is to copy the __name__ of the decorated function in the decorator.
It is a wrapper on update_wrapper
from functools import wraps def wrap1(func): @wraps(func) # 去掉就会返回inner def inner(*args): print(func.__name__) return func(*args) return inner @wrap1 def demo(): print('hello world') print(demo.__name__) # demo
reduce
In Python2, it is equivalent to the built-in function reduce
The function of the function is to summarize a sequence For an output
reduce(function, sequence, startValue) from functools import reduce l = range(1,50) print(reduce(lambda x,y:x+y, l)) # 1225
cmp_to_key
There is a key parameter in list.sort and the built-in function sorted
x = ['hello','worl','ni'] x.sort(key=len) print(x) # ['ni', 'worl', 'hello']
Before Python3, the cmp parameter was also provided to compare two The element
cmp_to_key function is used to convert the old comparison function into the key function
lru_cache
allows us to quickly cache or uncache the return value of a function.
This decorator is used to cache the call results of functions. For functions that need to be called multiple times, and the parameters are the same for each call, you can use this decorator to cache the call results, thereby speeding up the program.
This decorator will cache different call results in memory, so you need to pay attention to the memory usage issue.
from functools import lru_cache @lru_cache(maxsize=30) # maxsize参数告诉lru_cache缓存最近多少个返回值 def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) print([fib(n) for n in range(10)]) fib.cache_clear() # 清空缓存
singledispatch
Single dispatcher, new in Python3.4, is used to implement generic functions.
Determine which function to call based on the type of a single parameter.
from functools import singledispatch @singledispatch def fun(text): print('String:' + text) @fun.register(int) def _(text): print(text) @fun.register(list) def _(text): for k, v in enumerate(text): print(k, v) @fun.register(float) @fun.register(tuple) def _(text): print('float, tuple') fun('i am is hubo') fun(123) fun(['a','b','c']) fun(1.23) print(fun.registry) # 所有的泛型函数 print(fun.registry[int]) # 获取int的泛型函数 # String:i am is hubo # 123 # 0 a # 1 b # 2 c # float, tuple # {<class 'object'>: <function fun at 0x106d10f28>, <class 'int'>: <function _ at 0x106f0b9d8>, <class 'list'>: <function _ at 0x106f0ba60>, <class 'tuple'>: <function _ at 0x106f0bb70>, <class 'float'>: <function _ at 0x106f0bb70>} # <function _ at 0x106f0b9d8>
【Related recommendations: Python3 video tutorial】
The above is the detailed content of Summary of using Python's functools module. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

Pylance type detection problem solution when using custom decorator In Python programming, decorator is a powerful tool that can be used to add rows...

About Pythonasyncio...

Using python in Linux terminal...

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

Compatibility issues between Python asynchronous libraries In Python, asynchronous programming has become the process of high concurrency and I/O...

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

The problem and solution of the child process continuing to run when using signals to kill the parent process. In Python programming, after killing the parent process through signals, the child process still...
