python函式修飾符 的使用

2021-09-25 07:27:04 字數 3632 閱讀 1473

python函式修飾符@的作用是為現有函式增加額外的功能,常用於插入日誌、效能測試、事務處理等等。

建立函式修飾符的規則:

(1)修飾符是乙個函式

(2)修飾符取被修飾函式為引數

(3)修飾符返回乙個新函式

(4)修飾符維護被維護函式的簽名

例子1:被修飾函式不帶引數

---

----

----

----

----

----

----

----

----

----

----

----

----

----

----

----

----

- 注:如果你對python感興趣,我這有個學習python基地,裡面有很多學習資料,感興趣的+q群:895817687--

----

----

----

----

----

----

----

----

----

----

----

----

----

----

----

----

--deflog

(func)

:def()

:print

('log開始 ...'

) func(

)print

('log結束 ...'

)

@log

deftest()

:print

('test ..'

)test(

)

執行結果:

log開始 …

test …

log結束 .

例子2:使用functools模組提供的修改函式屬性的方法wraps

def

log(func)

:def()

:print

('log開始 ...'

) func(

)print

('log結束 ...'

)

@log

deftest1()

:print

('test1 ..'

)def

test2()

:print

('test2 ..'

)print

(test1.__name__)

print

(test2.__name__)

執行結果:

可見test1的函式名稱變了,如果某些**用到就會出問題,可以使用functools模組提供的修改函式屬性的方法wraps

from functools import wraps

deflog

(func)

: @wraps(func)

def():

print

('log開始 ...'

) func(

)print

('log結束 ...'

)

@log

deftest1()

:print

('test1 ..'

)def

test2()

:print

('test2 ..'

)print

(test1.__name__)

print

(test2.__name__)

執行結果:

test1

test2

例子3:被修飾函式帶引數

from functools import wraps

deflog

(func)

: @wraps(func)

def(

*args,

**kwargs)

:print

('log開始 ...'

,func.__name__)

ret = func(

*args,

**kwargs)

print

('log結束 ...'

)return ret

@log

deftest1

(s):

print

('test1 ..'

, s)

return s

@log

deftest2

(s1, s2)

:print

('test2 ..'

, s1, s2)

return s1 + s2

test1(

'a')

test2(

'a',

'bc'

)

執行結果:

log開始 … test1

test1 … a

log結束 …

log開始 … test2

test2 … a bc

log結束 …

例子4:修飾符帶引數,需要比上面例子多一層包裝

from functools import wraps

deflog

(arg)

:def

_log

(func)

: @wraps(func)

def(

*args,

**kwargs)

:print

('log開始 ...'

,func.__name__, arg)

ret = func(

*args,

**kwargs)

print

('log結束 ...'

)return ret

return _log

@log(

'module1'

)def

test1

(s):

print

('test1 ..'

, s)

return s

@log(

'module1'

)def

test2

(s1, s2)

:print

('test2 ..'

, s1, s2)

return s1 + s2

test1(

'a')

test2(

'a',

'bc'

)

執行結果:

log開始 … test1 module1

test1 … a

log結束 …

log開始 … test2 module1

test2 … a bc

log結束 …

python 修飾符 python 修飾符

修飾符基礎 閉包 什麼是閉包呢?標準的概念大家可以看wikipedia上的解釋 舉個例子 def do add base def add increase return base increase return add do add函式裡巢狀了乙個內層函式add,這個內層函式就是乙個閉包,其實可以也...

python 函式修飾符

def log func print log開始 func print log結束 如果log函式返回乙個字串,test就是乙個字串了 print test 輸出 log開始 test log結束 可見,test函式被替換了,但是其 name 屬性也變了。替換以後函式的一些屬性改變了,如 name ...

python 修飾符 python訪問修飾符

許可權訪問 偽許可權,只是壓縮時按規則換了變數名,python 的哲學是假定使用者都會使用 xx 以單下劃線開頭的表示的是protected型別的變數。即保護型別只能允許其本身與子類進行訪問。若內部變數標示,如 當使用 from m import 時,不會將以乙個下劃線開頭的物件引入 成俗約定,不做...