python重寫和裝飾器 python中的裝飾器

2021-10-21 07:57:15 字數 1966 閱讀 6777

裝飾器的本質:

當你在用某個@decorator來修飾某個函式func時,如下所示:

@decorator

def func():

pass

其直譯器會解釋成下面這樣的語句:

func=decorator(func)

本質是把乙個函式當作引數傳遞到另乙個函式中,然後再呼叫。

def hello(fn):

print "hello,%s" %fn.__name__

fn()

print "goodbye,%s" %fn.__name__

@hello

def foo():

print "i am foo"

>>>foo()

"hello,foo"

"i am foo"

"goodbye,foo"

多個裝飾器:

@decorator_one

@decorator_two

def func():

pass

相當於func=decorator_one(decorator_two(func))

帶引數的裝飾器:

@decorator(arg1,arg2)

def func():

pass

相當於func=decorator(arg1,arg2)(func).這意味著decorator(arg1,arg2)這個函式需要返回乙個「真正的裝飾器」。

def mydecorator(arg1,arg2):

def _mydecorator1(func):

def _mydecorator2(*args,**kw):

res=func(*args,**kw)

return res

return _mydecorator2

return _mydecorator1

上面的函式返回的_mydecorator1才是真正的裝飾器。因此,當裝飾器需要引數時,必須使用第二集封裝。因為裝飾器在模組第一次被讀取時由解釋程式裝入,所以它們的使用必須受限於總體上可以應用的封裝器。

帶引數及多個裝飾器:

def makehtmltag(tag,*args,**kwds):

def real_decorator(fn):

css_class="class=『『".format(kwds["css_class"]) if "css_class" in kwds else ""

return ""+fn(*args,**kwds)+""+tag+">"

return warpped(*args,**kwds)

return real_decorator

@makehtmltag(tag=『i『,css_class=『italic_css『)

@makehtmltag(tag=『b『,css_class=『bold_css『)

def hello():

return "hello world"

>>>hello()

hello world

class式裝飾器:

class mydecorator(object):

def __init__(self,fn):

print "inside mydecorator--init"

self.fn=fn

def __call__(self):

self.fn()

print "inside mydecorator--call"

@mydecorator

def myfunc():

print "inside myfunc"

>>>myfunc

"inside mydecorator--init"

"inside myfunc"

"inside mydecorator--call"

重寫makehtmltag**:

原文:

python 裝飾器和 property裝飾器

裝飾器 1 裝飾器函式的本質 乙個閉包函式 2 裝飾器函式的作用 在不修改原函式及其呼叫方式的情況下對原函式功能進行擴充套件 3 語法糖 格式 裝飾器名稱 4 建立帶返回值的裝飾器 5 建立傳遞引數的裝飾器 6 裝飾器的固定格式 def f definner args,kwargs ret f ar...

python裝飾器 Python 裝飾器

簡言之,python裝飾器就是用於拓展原來函式功能的一種函式,這個函式的特殊之處在於它的返回值也是乙個函式,使用python裝飾器的好處就是在不用更改原函式的 前提下給函式增加新的功能。一般而言,我們要想拓展原來函式 最直接的辦法就是侵入 裡面修改,例如 這是我們最原始的的乙個函式,然後我們試圖記錄...

python裝飾器 裝飾器

由於函式也是乙個物件,而且函式物件可以被賦值給變數,所以,通過變數也能呼叫該函式。def now print 2015 3 25 f now f 2015 3 25 函式物件有乙個 name 屬性,可以拿到函式的名字 now.name now f.name now 現在,假設我們要增強now 函式的...