使用functools模組wrap方法裝飾函式

2021-07-13 10:17:50 字數 2482 閱讀 3837

今天無意間看到python中的functools模組,發現使用這個模組的wraps()可以實現一些類似***的功能,比如:包裝異常,隱藏異常,列印日誌,統計函式使用時間等。下面就通過幾個**片段來看看具體使用方法:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import functools

defwrap_exception

(func):

@functools.wraps(func)

def(self, *args, **kwargs):

try:

return func(self, *args, **kwargs)

except baseexception as ex:

raise myexception(ex.message)

class

myexception

(exception):

def__init__

(self, msg):

self.msg = msg

def__str__

(self):

return self.msg

def__repr__

(self):

return self.msg

class

test:

def__init__

(self):

pass

@wrap_exception

deftest

(self):

raise exception("hello")

t = test()

t.test()

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import functools

defwrap_exception

(func):

@functools.wraps(func)

def(self, *args, **kwargs):

try:

return func(self, *args, **kwargs)

except:

pass

class

test:

def__init__

(self):

pass

@wrap_exception

deftest

(self):

raise exception("hello")

t = test()

t.test()

#!/usr/bin/env python

# -*- coding: utf-8 -*-

defwrap_logger

(func):

@functools.wraps(func)

def(self, *args, **kwargs):

print ("%s(%s, %s)" % (func, args, kwargs))

print

"before execute"

result = func(self, *args, **kwargs)

print

"after execute"

return result

class

test:

def__init__

(self):

pass

@wrap_logger

deftest

(self, a, b, c):

print a, b, c

t = test()

t.test(1, 2, 3)

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import functools

import time

defwrap_performance

(func):

@functools.wraps(func)

def(self, *args, **kwargs):

t_begin = time.time()

result = func(self, *args, **kwargs)

t_end = time.time()

print("time: %f " % (t_end - t_begin))

return result

class

test:

def__init__

(self):

pass

@wrap_performance

deftest

(self):

time.sleep(1)

t = test()

t.test()

Python標準模組 functools

functools,用於高階函式 指那些作用於函式或者返回其它函式的函式,通常只要是可以被當做函式呼叫的物件就是這個模組的目標。在python 2.7 中具備如下方法,cmp to key,將乙個比較函式轉換關鍵字函式 partial,針對函式起作用,並且是部分的 reduce,與python內建的...

Python標準模組 functools

functools,用於高階函式 指那些作用於函式或者返回其它函式的函式,通常只要是可以被當做函式呼叫的物件就是這個模組的目標。在python 2.7 中具備如下方法,cmp to key,將乙個比較函式轉換關鍵字函式 partial,針對函式起作用,並且是部分的 reduce,與python內建的...

functools模組中partial的使用

functools.partial func args 關鍵字 返回乙個新的部分物件 當被呼叫時,其行為類似於 使用位置引數 args 和關鍵字引數 關鍵字呼叫的 func args 如果提供了其他關鍵字引數,則它們會擴充套件和覆蓋 關鍵字。簡單說就是把乙個函式,和該函式所需傳的引數封裝到乙個cla...