python3 修饰器_【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
總結
以上是生活随笔為你收集整理的python3 修饰器_【python3】修饰器简单理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3urllib中的quote
- 下一篇: python运算符讲解_3.Python