装饰器

装饰器

定义:本质是函数,(装饰其他函数),就是为其他函数添加附加功能

原则:1.不能修改被装饰的函数的源代码

   2.不能修改被装饰的函数的调用方式

 

实现装饰器知识储备:

1. 函数 即 “变量” ,
定义一个函数,相当于把函数体,赋值给函数名;变量有内存回收机制。函数也即有内存回收;门牌号存在,房间就不会被删,门牌号不存在,房间就没了

 

2. 高阶函数

  a: 把一个函数名当作实参传给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)

import time
def bar():
    time.sleep(3)
    print('in the bar')

def test1(func):
    start_time=time.time()
    func()  #run bar
    stop_time=time.time()
    print("the func run time is %s" %(stop_time-start_time))

test1(bar)

# 运行结果
# in the bar
# the func run time is 3.0009970664978027

   b: 返回值中包含函数名(不修改函数的调用方式)

import time
def bar():
    time.sleep(3)
    print('in the bar')
def test2(func):
    print(func)
    return func

bar=test2(bar)
bar()   #run bar

#运行结果
#<function bar at 0x0000026CC56F3E18>
#in the bar

 

3. 嵌套函数

def foo():
    print('in the foo')
    def bar():
        print('in the bar')
    bar()
foo()

 

 

高阶函数 + 嵌套函数 = 》 装饰器

import time
def timer(func): #timer(test1)  func=test1
    def deco():
        start_time=time.time()
        func()  #run test1()
        stop_time=time.time()
        print("the func run time is %s" %(stop_time-start_time))
    return deco  #返回deco的内存地址

@timer  #test1=timer(test1)
def test1():
    time.sleep(3)
    print('in the test1')

test1()   #-->deco

#运行结果
#in the test1
#the func run time is 3.000441074371338

 

升级版

import time
user,passwd = "alex","abc123"
def auth(func):
    def wrapper(*args,**kwargs):
        username = input("Username:").strip()
        password = input("Password:").strip()
        if user == username and passwd == password:
            print("\033[32;1mUser has passed authentication\033[0m")
            func(*args,**kwargs)
        else:
            exit("\033[31;1mInvalid username or password\033[0m")
    return wrapper

def index():
    print("welcome to index page")

@auth
def home():
    print("welcome to home page")

@auth
def bbs():
    print("welcome to bbs page")


index()
home()
bbs()

 

posted @ 2017-08-24 09:37  _Cohen  阅读(114)  评论(0)    收藏  举报