python 裝飾器

概述

  瞭解裝飾器以前先了解下什麼是閉包,內部函數調用外部變量的行爲叫作閉包。裝飾器就是閉包的一種,裝飾器做用是可讓你代碼看上去更簡潔。如下詳細介紹了閉包代碼和裝飾器代碼(閉包調用函數外部變量延長了外部變量的生命週期而普通函數進入另個一個函數是變量就沒法再用。)html

詳解

1)閉包是內部函數調用外部變量python

2)裝飾器是閉包的一種閉包

3)裝飾器調用的外部變量是一個函數app

4)裝飾器來修飾函數,不用重複修改函數或者增長新的封裝。函數

5)修飾符提升了程序的可重複利用性,並增長了程序的可讀性代碼看上去更簡潔ui

代碼

閉包spa

def waiBu(name):
    def neiQian():
        print('my name is ',name)
    #1)調用內部函數
    #2)調用的內部函數是針對waiBu()函數來說的
    #3)閉包中return內容只能return當前函數內嵌函數,不能return內嵌函數的內嵌函數
    #4)能夠return當前函數再被外層函數return
    #5)內嵌的內嵌函數可使用最外層的函數參數
    return neiQian()
#針對上面註釋3/4/5的代碼示例以下:
#def waiBu(name):
#    def neiQian():
#        def neiQian1():
#           def neiQian2():
#                print('my name is',name)
#            return neiQian2()
#        return neiQian1()
#    return neiQian()

if __name__=='__main__':
    #輸出'my name is tory'
    waiBu('tory')

 

 

裝飾器詳解1:.net

def a_new_decorator(a_func):
 
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
 
        a_func()
 
        print("I am doing some boring work after executing a_func()")
 
    return wrapTheFunction
 
def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")
 
a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
 
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
 
a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

裝飾器詳解2:這裏咱們能夠用@簡短方式來生成一個被裝飾代碼,爲了避免重寫原有代碼須要在原有代碼加上@wraps修飾符code

from functools import wraps
 
def a_new_decorator(a_func):
    @wraps(a_func)
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction #此處由於函數a_func做爲變量,因此不須要retrun wrapTheFunction或a_newdecorator(a_func)()
 
@a_new_decorator
def a_function_requiring_decoration():
    """Hey yo! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")
 
print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration
from functools import wraps
def decorator_name(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not can_run:
            return "Function will not run"
        return f(*args, **kwargs)
    return decorated
 
@decorator_name
def func():
    return("Function is running")
 
can_run = True
print(func())
# Output: Function is running
 
can_run = False
print(func())
# Output: Function will not run

裝飾器的應用場景htm

 

#!/usr/bin/env python
import logging
def use_logging(func):
    def wrapper():
        logging.warn("%s is running" % func.__name__)#運行時控制檯輸出..
        return func()
    return wrapper 
@use_logging
def foo():
    print("i am foo")
foo()

 

 

 

參考連接

https://www.runoob.com/w3cnote/python-func-decorators.html

http://www.javashuo.com/article/p-baoakhuc-dn.html

http://www.javashuo.com/article/p-flvqncmm-gp.html

http://www.javashuo.com/article/p-gwkwrmft-da.html

相關文章
相關標籤/搜索