欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python functools模塊學習總結

 更新時間:2015年05月09日 12:02:36   投稿:junjie  
這篇文章主要介紹了Python functools模塊學習總結,本文講解了functools.partial、functool.update_wrapper、functool.wraps、functools.reduce、functools.cmp_to_key、functools.total_ordering等方法的使用實例,需要的朋友可以參考下

文檔 地址

functools.partial

作用:

functools.partial 通過包裝手法,允許我們 "重新定義" 函數簽名

用一些默認參數包裝一個可調用對象,返回結果是可調用對象,并且可以像原始對象一樣對待

凍結部分函數位置函數或關鍵字參數,簡化函數,更少更靈活的函數參數調用

復制代碼 代碼如下:

#args/keywords 調用partial時參數
def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords) #合并,調用原始函數,此時用了partial的參數
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

聲明:
復制代碼 代碼如下:

urlunquote = functools.partial(urlunquote, encoding='latin1')

當調用 urlunquote(args, *kargs)

相當于 urlunquote(args, *kargs, encoding='latin1')

E.g:

復制代碼 代碼如下:

import functools

def add(a, b):
    return a + b

add(4, 2)
6

plus3 = functools.partial(add, 3)
plus5 = functools.partial(add, 5)

plus3(4)
7
plus3(7)
10

plus5(10)
15

應用:

典型的,函數在執(zhí)行時,要帶上所有必要的參數進行調用。

然后,有時參數可以在函數被調用之前提前獲知。

這種情況下,一個函數有一個或多個參數預先就能用上,以便函數能用更少的參數進行調用。

functool.update_wrapper

默認partial對象沒有__name__和__doc__, 這種情況下,對于裝飾器函數非常難以debug.使用update_wrapper(),從原始對象拷貝或加入現有partial對象

它可以把被封裝函數的__name__、module、__doc__和 __dict__都復制到封裝函數去(模塊級別常量WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES)

復制代碼 代碼如下:

>>> functools.WRAPPER_ASSIGNMENTS
('__module__', '__name__', '__doc__')
>>> functools.WRAPPER_UPDATES
('__dict__',)

這個函數主要用在裝飾器函數中,裝飾器返回函數反射得到的是包裝函數的函數定義而不是原始函數定義

復制代碼 代碼如下:

#!/usr/bin/env python
# encoding: utf-8

def wrap(func):
    def call_it(*args, **kwargs):
        """wrap func: call_it"""
        print 'before call'
        return func(*args, **kwargs)
    return call_it

@wrap
def hello():
    """say hello"""
    print 'hello world'

from functools import update_wrapper
def wrap2(func):
    def call_it(*args, **kwargs):
        """wrap func: call_it2"""
        print 'before call'
        return func(*args, **kwargs)
    return update_wrapper(call_it, func)

@wrap2
def hello2():
    """test hello"""
    print 'hello world2'

if __name__ == '__main__':
    hello()
    print hello.__name__
    print hello.__doc__

    print
    hello2()
    print hello2.__name__
    print hello2.__doc__

得到結果:

復制代碼 代碼如下:

before call
hello world
call_it
wrap func: call_it

before call
hello world2
hello2
test hello

functool.wraps

調用函數裝飾器partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)的簡寫

復制代碼 代碼如下:

from functools import wraps
def wrap3(func):
    @wraps(func)
    def call_it(*args, **kwargs):
        """wrap func: call_it2"""
        print 'before call'
        return func(*args, **kwargs)
    return call_it

@wrap3
def hello3():
    """test hello 3"""
    print 'hello world3'


結果
復制代碼 代碼如下:

before call
hello world3
hello3
test hello 3

functools.reduce

復制代碼 代碼如下:

functools.reduce(function, iterable[, initializer])

等同于內置函數reduce()

用這個的原因是使代碼更兼容(python3)

functools.cmp_to_key

functools.cmp_to_key(func)
將老式鼻尖函數轉換成key函數,用在接受key函數的方法中(such as sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby())

一個比較函數,接收兩個參數,小于,返回負數,等于,返回0,大于返回整數

key函數,接收一個參數,返回一個表明該參數在期望序列中的位置

例如:

復制代碼 代碼如下:

sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order

functools.total_ordering

復制代碼 代碼如下:

functools.total_ordering(cls)

這個裝飾器是在python2.7的時候加上的,它是針對某個類如果定義了__lt__、le、gt、__ge__這些方法中的至少一個,使用該裝飾器,則會自動的把其他幾個比較函數也實現在該類中
復制代碼 代碼如下:

@total_ordering
class Student:
    def __eq__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))
print dir(Student)

得到
復制代碼 代碼如下:

['__doc__', '__eq__', '__ge__', '__gt__', '__le__', '__lt__', '__module__']

相關文章

  • 創(chuàng)建Python Docker鏡像的詳細步驟

    創(chuàng)建Python Docker鏡像的詳細步驟

    Python和Docker是兩個極其流行的技術,結合它們可以創(chuàng)建強大的應用程序,Docker允許將應用程序及其依賴項打包到一個獨立的容器中,而Python則提供了豐富的庫和工具來開發(fā)應用程序,本文將提供如何創(chuàng)建Python Docker鏡像的全面指南,,需要的朋友可以參考下
    2023-12-12
  • Python操作列表常用方法實例小結【創(chuàng)建、遍歷、統(tǒng)計、切片等】

    Python操作列表常用方法實例小結【創(chuàng)建、遍歷、統(tǒng)計、切片等】

    這篇文章主要介紹了Python操作列表常用方法,結合實例形式總結分析了Python列表常見的創(chuàng)建、遍歷、統(tǒng)計、切片等操作技巧與相關注意事項,需要的朋友可以參考下
    2019-10-10
  • python request post 列表的方法詳解

    python request post 列表的方法詳解

    這篇文章主要介紹了python request post 列表的方法詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • Python如何將將模塊分割成多個文件

    Python如何將將模塊分割成多個文件

    這篇文章主要介紹了Python如何將將模塊分割成多個文件,文中講解非常細致,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-08-08
  • Django的get_absolute_url方法的使用

    Django的get_absolute_url方法的使用

    本文主要介紹了Django的get_absolute_url方法的使用,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • Python通過串口實現收發(fā)文件

    Python通過串口實現收發(fā)文件

    這篇文章主要為大家詳細介紹了Python如何通過串口實現收發(fā)文件功能,文中的示例代碼簡潔易懂,具有一定的借鑒價值,感興趣的小伙伴可以跟隨小編一起學習一下
    2023-11-11
  • python進程池實現的多進程文件夾copy器完整示例

    python進程池實現的多進程文件夾copy器完整示例

    這篇文章主要介紹了python進程池實現的多進程文件夾copy器,結合完整實例形式分析了Python基于多進程與進程池的文件操作相關實現技巧,需要的朋友可以參考下
    2019-11-11
  • Django框架之路由用法

    Django框架之路由用法

    這篇文章介紹了Django框架之路由的用法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • python檢查指定文件是否存在的方法

    python檢查指定文件是否存在的方法

    這篇文章主要介紹了python檢查指定文件是否存在的方法,涉及Python基于os模塊判定文件的相關技巧,非常簡單實用,需要的朋友可以參考下
    2015-07-07
  • Python中@符號的具體使用

    Python中@符號的具體使用

    本文主要介紹了Python中@符號的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-06-06

最新評論