Python札記 裝飾器補充

2021-06-26 06:06:45 字數 1434 閱讀 2559

本隨筆是對python札記 -- 裝飾器的一些補充。

使用裝飾器的時候,被裝飾函式的一些屬性會丟失,比如如下**:

#!/usr/bin/env python

def deco(func):

print "wrap start"

func()

print "wrap end\n"

@deco

def foo():

"""docstring for foo"""

print "in foo():"

foo()

print foo.__name__

print foo.__doc__

輸出如下:

$ python decorator_test.py

wrap start

in foo():

wrap end

none

#!/usr/bin/env python

def deco(func):

print "wrap start"

func()

print "wrap end\n"

@deco

def foo():

"""docstring for foo"""

print "in foo():"

foo()

print foo.__name__

print foo.__doc__

decorator_test_with_wraps.py

#!/usr/bin/env python

from functools import wraps

def deco(func):

@wraps(func) #使用裝飾器來實現

print "wrap start"

func()

print "wrap end\n"

@deco

def foo():

"""docstring for foo"""

print "in foo():"

foo()

print foo.__name__

print foo.__doc__

現在被deco裝飾過的foo方法,可以保留之前的__name__和__doc__屬性了。

wrap start

in foo():

wrap end

foodocstring for foo

$ python decorator_test_with_wraps.py

wrap start

in foo():

wrap end

foodocstring for foo

python 裝飾器 補充

在寫python類的時候,雖然可以通過 例項名.變數名 的方式對例項中的變數進行讀取和賦值。但出於規範性等等原因,我們最好還是寫getter和setter,使用property 函式和 property修飾符。第一種方法,使用property 函式 class person def init sel...

補充裝飾器

1.用functools.wraps隱藏包裝函式 先實現乙個簡單的裝飾器,過濾非負引數 def decorate func def wrap args,kwargs return return wrap myfilter def test args print args is s args 可以發現...

裝飾器補充

一 通用裝飾器回顧 def inner args,kwargs 執行目標函式之前要執行的內容 ret func args,kwargs 執行目標函式之後要執行的內容 return ret return inner def target func print 我是目標函式 呼叫目標函式 二 函式的有用...