<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](operator.xhtml "operator --- 標準運算符替代函數") | - [上一頁](itertools.xhtml "itertools --- 為高效循環而創建迭代器的函數") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 標準庫](index.xhtml) ? - [函數式編程模塊](functional.xhtml) ? - $('.inline-search').show(0); | # [`functools`](#module-functools "functools: Higher-order functions and operations on callable objects.") --- 高階函數和可調用對象上的操作 **源代碼:** [Lib/functools.py](https://github.com/python/cpython/tree/3.7/Lib/functools.py) \[https://github.com/python/cpython/tree/3.7/Lib/functools.py\] - - - - - - [`functools`](#module-functools "functools: Higher-order functions and operations on callable objects.") 模塊應用于高階函數,即——參數或(和)返回值為其他函數的函數。通常來說,此模塊的功能適用于所有可調用對象。 [`functools`](#module-functools "functools: Higher-order functions and operations on callable objects.") 模塊定義了以下函數: `functools.``cmp_to_key`(*func*)將(舊式的)比較函數轉換為新式的 [key function](../glossary.xhtml#term-key-function) . 在類似于 [`sorted()`](functions.xhtml#sorted "sorted") , [`min()`](functions.xhtml#min "min") , [`max()`](functions.xhtml#max "max") , [`heapq.nlargest()`](heapq.xhtml#heapq.nlargest "heapq.nlargest") , [`heapq.nsmallest()`](heapq.xhtml#heapq.nsmallest "heapq.nsmallest") , [`itertools.groupby()`](itertools.xhtml#itertools.groupby "itertools.groupby") 等函數的 key 參數中使用。此函數主要用作將 Python 2 程序轉換至新版的轉換工具,以保持對比較函數的兼容。 比較函數意為一個可調用對象,該對象接受兩個參數并比較它們,結果為小于則返回一個負數,相等則返回零,大于則返回一個正數。key function則是一個接受一個參數,并返回另一個用以排序的值的可調用對象。 示例: ``` sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order ``` 有關排序示例和簡要排序教程,請參閱 [排序指南](../howto/sorting.xhtml#sortinghowto) 。 3\.2 新版功能. `@``functools.``lru_cache`(*maxsize=128*, *typed=False*)一個提供緩存功能的裝飾器,包裝一個函數,緩存其\*maxsize\*組傳入參數,在下次以相同參數調用時直接返回上一次的結果。用以節約高開銷或I/O函數的調用時間。 由于使用了字典存儲緩存,所以該函數的固定參數和關鍵字參數必須是可哈希的。 不同模式的參數可能被視為不同從而產生多個緩存項,例如, f(a=1, b=2) 和 f(b=2, a=1) 因其參數順序不同,可能會被緩存兩次。 如果 *maxsize* 設置為 `None` ,LRU功能將被禁用且緩存數量無上限。 *maxsize* 設置為2的冪時可獲得最佳性能。 如果 *typed* 設置為true,不同類型的函數參數將被分別緩存。例如, `f(3)` 和 `f(3.0)` 將被視為不同而分別緩存。 To help measure the effectiveness of the cache and tune the *maxsize*parameter, the wrapped function is instrumented with a `cache_info()`function that returns a [named tuple](../glossary.xhtml#term-named-tuple) showing *hits*, *misses*, *maxsize* and *currsize*. In a multi-threaded environment, the hits and misses are approximate. 該裝飾器也提供了一個用于清理/使緩存失效的函數 `cache_clear()` 。 The original underlying function is accessible through the `__wrapped__` attribute. This is useful for introspection, for bypassing the cache, or for rewrapping the function with a different cache. “最久未使用算法”(LRU) 緩存 算法鏈接:<[https://en.wikipedia.org/wiki/Cache\_algorithms#Examples](https://en.wikipedia.org/wiki/Cache_algorithms#Examples)> 這個緩存在“最近的調用是即將到來的調用的最佳預測因子”時性能最好,(比如,新聞服務器上最受歡迎的文章傾向于每天更改)。“緩存大小限制”參數保證緩存不會在長時間運行的進程比如說網站服務器上無限制的增加自身的大小。 一般來說,LRU緩存只在當你想要重用之前計算的結果時使用。因此,用它緩存具有副作用的函數、需要在每次調用時創建不同、易變的對象的函數或者諸如time()或random()之類的不純函數是沒有意義的。 靜態 Web 內容的 LRU 緩存示例: ``` @lru_cache(maxsize=32) def get_pep(num): 'Retrieve text of a Python Enhancement Proposal' resource = 'http://www.python.org/dev/peps/pep-%04d/' % num try: with urllib.request.urlopen(resource) as s: return s.read() except urllib.error.HTTPError: return 'Not Found' >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991: ... pep = get_pep(n) ... print(n, len(pep)) >>> get_pep.cache_info() CacheInfo(hits=3, misses=8, maxsize=32, currsize=8) ``` Example of efficiently computing [Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number) \[https://en.wikipedia.org/wiki/Fibonacci\_number\]using a cache to implement a [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) \[https://en.wikipedia.org/wiki/Dynamic\_programming\]technique: ``` @lru_cache(maxsize=None) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) >>> [fib(n) for n in range(16)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] >>> fib.cache_info() CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) ``` 3\.2 新版功能. 在 3.3 版更改: 添加 *typed* 選項。 `@``functools.``total_ordering`Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest. This simplifies the effort involved in specifying all of the possible rich comparison operations: The class must define one of [`__lt__()`](../reference/datamodel.xhtml#object.__lt__ "object.__lt__"), [`__le__()`](../reference/datamodel.xhtml#object.__le__ "object.__le__"), [`__gt__()`](../reference/datamodel.xhtml#object.__gt__ "object.__gt__"), or [`__ge__()`](../reference/datamodel.xhtml#object.__ge__ "object.__ge__"). In addition, the class should supply an [`__eq__()`](../reference/datamodel.xhtml#object.__eq__ "object.__eq__") method. 例如: ``` @total_ordering class Student: def _is_valid_operand(self, other): return (hasattr(other, "lastname") and hasattr(other, "firstname")) def __eq__(self, other): if not self._is_valid_operand(other): return NotImplemented return ((self.lastname.lower(), self.firstname.lower()) == (other.lastname.lower(), other.firstname.lower())) def __lt__(self, other): if not self._is_valid_operand(other): return NotImplemented return ((self.lastname.lower(), self.firstname.lower()) < (other.lastname.lower(), other.firstname.lower())) ``` 注解 While this decorator makes it easy to create well behaved totally ordered types, it *does* come at the cost of slower execution and more complex stack traces for the derived comparison methods. If performance benchmarking indicates this is a bottleneck for a given application, implementing all six rich comparison methods instead is likely to provide an easy speed boost. 3\.2 新版功能. 在 3.4 版更改: Returning NotImplemented from the underlying comparison function for unrecognised types is now supported. `functools.``partial`(*func*, *\*args*, *\*\*keywords*)Return a new [partial object](#partial-objects) 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: ``` 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 ``` The [`partial()`](#functools.partial "functools.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()`](#functools.partial "functools.partial") can be used to create a callable that behaves like the [`int()`](functions.xhtml#int "int") function where the *base* argument defaults to two: ``` >>> from functools import partial >>> basetwo = partial(int, base=2) >>> basetwo.__doc__ = 'Convert base 2 string to an int.' >>> basetwo('10010') 18 ``` *class* `functools.``partialmethod`(*func*, *\*args*, *\*\*keywords*)Return a new [`partialmethod`](#functools.partialmethod "functools.partialmethod") descriptor which behaves like [`partial`](#functools.partial "functools.partial") except that it is designed to be used as a method definition rather than being directly callable. *func* must be a [descriptor](../glossary.xhtml#term-descriptor) or a callable (objects which are both, like normal functions, are handled as descriptors). When *func* is a descriptor (such as a normal Python function, [`classmethod()`](functions.xhtml#classmethod "classmethod"), [`staticmethod()`](functions.xhtml#staticmethod "staticmethod"), `abstractmethod()` or another instance of [`partialmethod`](#functools.partialmethod "functools.partialmethod")), calls to `__get__` are delegated to the underlying descriptor, and an appropriate [partial object](#partial-objects) returned as the result. When *func* is a non-descriptor callable, an appropriate bound method is created dynamically. This behaves like a normal Python function when used as a method: the *self* argument will be inserted as the first positional argument, even before the *args* and *keywords* supplied to the [`partialmethod`](#functools.partialmethod "functools.partialmethod") constructor. 示例: ``` >>> class Cell(object): ... def __init__(self): ... self._alive = False ... @property ... def alive(self): ... return self._alive ... def set_state(self, state): ... self._alive = bool(state) ... set_alive = partialmethod(set_state, True) ... set_dead = partialmethod(set_state, False) ... >>> c = Cell() >>> c.alive False >>> c.set_alive() >>> c.alive True ``` 3\.4 新版功能. `functools.``reduce`(*function*, *iterable*\[, *initializer*\])Apply *function* of two arguments cumulatively to the items of *sequence*, from left to right, so as to reduce the sequence to a single value. For example, `reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])` calculates `((((1+2)+3)+4)+5)`. The left argument, *x*, is the accumulated value and the right argument, *y*, is the update value from the *sequence*. If the optional *initializer* is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If *initializer* is not given and *sequence* contains only one item, the first item is returned. 大致相當于: ``` def reduce(function, iterable, initializer=None): it = iter(iterable) if initializer is None: value = next(it) else: value = initializer for element in it: value = function(value, element) return value ``` `@``functools.``singledispatch`Transform a function into a [single-dispatch](../glossary.xhtml#term-single-dispatch) [generic function](../glossary.xhtml#term-generic-function). To define a generic function, decorate it with the `@singledispatch`decorator. Note that the dispatch happens on the type of the first argument, create your function accordingly: ``` >>> from functools import singledispatch >>> @singledispatch ... def fun(arg, verbose=False): ... if verbose: ... print("Let me just say,", end=" ") ... print(arg) ``` To add overloaded implementations to the function, use the `register()`attribute of the generic function. It is a decorator. For functions annotated with types, the decorator will infer the type of the first argument automatically: ``` >>> @fun.register ... def _(arg: int, verbose=False): ... if verbose: ... print("Strength in numbers, eh?", end=" ") ... print(arg) ... >>> @fun.register ... def _(arg: list, verbose=False): ... if verbose: ... print("Enumerate this:") ... for i, elem in enumerate(arg): ... print(i, elem) ``` For code which doesn't use type annotations, the appropriate type argument can be passed explicitly to the decorator itself: ``` >>> @fun.register(complex) ... def _(arg, verbose=False): ... if verbose: ... print("Better than complicated.", end=" ") ... print(arg.real, arg.imag) ... ``` To enable registering lambdas and pre-existing functions, the `register()` attribute can be used in a functional form: ``` >>> def nothing(arg, verbose=False): ... print("Nothing.") ... >>> fun.register(type(None), nothing) ``` The `register()` attribute returns the undecorated function which enables decorator stacking, pickling, as well as creating unit tests for each variant independently: ``` >>> @fun.register(float) ... @fun.register(Decimal) ... def fun_num(arg, verbose=False): ... if verbose: ... print("Half of your number:", end=" ") ... print(arg / 2) ... >>> fun_num is fun False ``` When called, the generic function dispatches on the type of the first argument: ``` >>> fun("Hello, world.") Hello, world. >>> fun("test.", verbose=True) Let me just say, test. >>> fun(42, verbose=True) Strength in numbers, eh? 42 >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True) Enumerate this: 0 spam 1 spam 2 eggs 3 spam >>> fun(None) Nothing. >>> fun(1.23) 0.615 ``` Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. The original function decorated with `@singledispatch` is registered for the base `object` type, which means it is used if no better implementation is found. To check which implementation will the generic function choose for a given type, use the `dispatch()` attribute: ``` >>> fun.dispatch(float) <function fun_num at 0x1035a2840> >>> fun.dispatch(dict) # note: default implementation <function fun at 0x103fe0000> ``` To access all registered implementations, use the read-only `registry`attribute: ``` >>> fun.registry.keys() dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>, <class 'decimal.Decimal'>, <class 'list'>, <class 'float'>]) >>> fun.registry[float] <function fun_num at 0x1035a2840> >>> fun.registry[object] <function fun at 0x103fe0000> ``` 3\.4 新版功能. 在 3.7 版更改: The `register()` attribute supports using type annotations. `functools.``update_wrapper`(*wrapper*, *wrapped*, *assigned=WRAPPER\_ASSIGNMENTS*, *updated=WRAPPER\_UPDATES*)Update a *wrapper* function to look like the *wrapped* function. The optional arguments are tuples to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function and which attributes of the wrapper function are updated with the corresponding attributes from the original function. The default values for these arguments are the module level constants `WRAPPER_ASSIGNMENTS` (which assigns to the wrapper function's `__module__`, `__name__`, `__qualname__`, `__annotations__`and `__doc__`, the documentation string) and `WRAPPER_UPDATES` (which updates the wrapper function's `__dict__`, i.e. the instance dictionary). To allow access to the original function for introspection and other purposes (e.g. bypassing a caching decorator such as [`lru_cache()`](#functools.lru_cache "functools.lru_cache")), this function automatically adds a `__wrapped__` attribute to the wrapper that refers to the function being wrapped. The main intended use for this function is in [decorator](../glossary.xhtml#term-decorator) functions which wrap the decorated function and return the wrapper. If the wrapper function is not updated, the metadata of the returned function will reflect the wrapper definition rather than the original function definition, which is typically less than helpful. [`update_wrapper()`](#functools.update_wrapper "functools.update_wrapper") may be used with callables other than functions. Any attributes named in *assigned* or *updated* that are missing from the object being wrapped are ignored (i.e. this function will not attempt to set them on the wrapper function). [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError") is still raised if the wrapper function itself is missing any attributes named in *updated*. 3\.2 新版功能: Automatic addition of the `__wrapped__` attribute. 3\.2 新版功能: Copying of the `__annotations__` attribute by default. 在 3.2 版更改: Missing attributes no longer trigger an [`AttributeError`](exceptions.xhtml#AttributeError "AttributeError"). 在 3.4 版更改: The `__wrapped__` attribute now always refers to the wrapped function, even if that function defined a `__wrapped__` attribute. (see [bpo-17482](https://bugs.python.org/issue17482) \[https://bugs.python.org/issue17482\]) `@``functools.``wraps`(*wrapped*, *assigned=WRAPPER\_ASSIGNMENTS*, *updated=WRAPPER\_UPDATES*)This is a convenience function for invoking [`update_wrapper()`](#functools.update_wrapper "functools.update_wrapper") as a function decorator when defining a wrapper function. It is equivalent to `partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)`. For example: ``` >>> from functools import wraps >>> def my_decorator(f): ... @wraps(f) ... def wrapper(*args, **kwds): ... print('Calling decorated function') ... return f(*args, **kwds) ... return wrapper ... >>> @my_decorator ... def example(): ... """Docstring""" ... print('Called example function') ... >>> example() Calling decorated function Called example function >>> example.__name__ 'example' >>> example.__doc__ 'Docstring' ``` Without the use of this decorator factory, the name of the example function would have been `'wrapper'`, and the docstring of the original `example()`would have been lost. ## [`partial`](#functools.partial "functools.partial") Objects [`partial`](#functools.partial "functools.partial") objects are callable objects created by [`partial()`](#functools.partial "functools.partial"). They have three read-only attributes: `partial.``func`A callable object or function. Calls to the [`partial`](#functools.partial "functools.partial") object will be forwarded to [`func`](#functools.partial.func "functools.partial.func") with new arguments and keywords. `partial.``args`The leftmost positional arguments that will be prepended to the positional arguments provided to a [`partial`](#functools.partial "functools.partial") object call. `partial.``keywords`The keyword arguments that will be supplied when the [`partial`](#functools.partial "functools.partial") object is called. [`partial`](#functools.partial "functools.partial") objects are like `function` objects in that they are callable, weak referencable, and can have attributes. There are some important differences. For instance, the [`__name__`](stdtypes.xhtml#definition.__name__ "definition.__name__") and `__doc__` attributes are not created automatically. Also, [`partial`](#functools.partial "functools.partial") objects defined in classes behave like static methods and do not transform into bound methods during instance attribute look-up. ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](operator.xhtml "operator --- 標準運算符替代函數") | - [上一頁](itertools.xhtml "itertools --- 為高效循環而創建迭代器的函數") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 標準庫](index.xhtml) ? - [函數式編程模塊](functional.xhtml) ? - $('.inline-search').show(0); | ? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看