【python3】修飾器簡單理解


修飾器

### 修飾器干嘛的,有什么作用 比如說A現在已經寫好了一個項目,但是現在B接管了這個項目,B需要對項目中的某個函數進行修改,一個一個修改然后復制,粘貼?這時候修飾器就開始大顯身手了。修飾器可以避免許多重復的動作。用@+修飾函數放在待修飾的函數頭上就可以實現優化函數的功能 ### 修飾器的理解 ####原函數沒有參數 修飾器可以看作是一個接收函數的函數,內部再定義局部函數用來修飾傳進來的函數參數 ``` def makebold(fn): def wrapped(): return "" + fn() + "" return wrapped

def makeitalic(fn):
def wrapped():
return "" + fn() + ""
return wrapped

@makebold
@makeitalic
def hello():
return "hello world"

print hello() ## 返回 hello world

####原函數有參數
修飾函數還是傳函數參數,修飾函數里面的局部函數傳入原函數的參數

def w2(fun):
def wrapper(args,**kwargs):
print("this is the wrapper head")
fun(
args,**kwargs)
print("this is the wrapper end")
return wrapper

@w2
def hello(name,name2):
print("hello"+name+name2)

hello("world","!!!")

輸出:

this is the wrapper head

helloworld!!!

this is the wrapper end

####需要有返回值

def w3(fun):
def wrapper():
print("this is the wrapper head")
temp=fun()
print("this is the wrapper end")
return temp #要把值傳回去呀!!
return wrapper

@w3
def hello():
print("hello")
return "test"

result=hello()
print("After the wrapper,I accept %s" %result)

輸出:

this is the wrapper head

hello

this is the wrapper end

After the wrapper,I accept test

####類修飾器
大體上和函數修飾器差不多,只是類不能直接調用要加上__call__方法。

class Test(object):
def init(self, func):
print('test init')
print('func name is %s ' % func.name)
self.__func = func

def __call__(self, *args, **kwargs):
    print('this is wrapper')
    self.__func()

@Test
def test():
print('this is test func')

test()

輸出:

test init

func name is test

this is wrapper

this is test func

</font>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM