python3 修饰器_【python3】修饰器简单理解
### 修飾器干嘛的,有什么作用
比如說A現(xiàn)在已經(jīng)寫好了一個(gè)項(xiàng)目,但是現(xiàn)在B接管了這個(gè)項(xiàng)目,B需要對(duì)項(xiàng)目中的某個(gè)函數(shù)進(jìn)行修改,一個(gè)一個(gè)修改然后復(fù)制,粘貼?這時(shí)候修飾器就開始大顯身手了。修飾器可以避免許多重復(fù)的動(dòng)作。用@+修飾函數(shù)放在待修飾的函數(shù)頭上就可以實(shí)現(xiàn)優(yōu)化函數(shù)的功能
### 修飾器的理解
####原函數(shù)沒有參數(shù)
修飾器可以看作是一個(gè)接收函數(shù)的函數(shù),內(nèi)部再定義局部函數(shù)用來修飾傳進(jìn)來的函數(shù)參數(shù)
```
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
####原函數(shù)有參數(shù)
修飾函數(shù)還是傳函數(shù)參數(shù),修飾函數(shù)里面的局部函數(shù)傳入原函數(shù)的參數(shù)
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
####類修飾器
大體上和函數(shù)修飾器差不多,只是類不能直接調(diào)用要加上__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
總結(jié)
以上是生活随笔為你收集整理的python3 修饰器_【python3】修饰器简单理解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3urllib中的quote
- 下一篇: python运算符讲解_3.Python