Python全栈之路Day20

初次编辑2017年10月26日,星期四

摘要

引用:Alex

  1. 装饰器
  2. 无参装饰器
  3. 有参装饰器

一. 上节课复习

  1. 名称空间与作用域
    1. 内置名称空间
    2. 全局名称空间
    3. 局部名称空间
    4. 全局作用域:内置名称空间、全局名称空间
    5. 局部作用域:局部名称空间
  2. 函数嵌套与嵌套作用域
  3. 函数对象
  4. 闭包

二. 装饰器

  1. 为什么要用装饰器及开放封闭原则
  2. 什么是装饰器
  3. 无参装饰器的简单实现
import time
def timmer(func):
    def wrapper():
        start_time = time.time()
        func()
        stop_time = time.time()
        print('run time is %s ' % (stop_time - start_time))
    return wrapper

@timmer        #index=timmer(index)
def index():
    time.sleep(3)
    print('welcome to oldboy')

index()        #wrapper()
  1. 无参装饰器修正part1
import  time
def timmer(func):
    def foo(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)
        stop_time = time.time()
        print('run time is %s' % (stop_time - start_time))
    return foo

@timmer    #index = timmer(index)
def index(name):
    time.sleep(2)
    print('welconme to my home! %s' % name)

@timmer    #auth = timmer(auth)
def auth(name,passwd):
    print(name,passwd)

index('egon')        #foo('egon')
auth('liuyang','123')    #foo('liuyang','123')
  1. 无参装饰器修正part2
import time
def timmer(func):
    def foo(*args,**kwargs):
        start_time = time.time()
        res = func(*args,**kwargs)
        stop_time = time.time()
        print('run time is %s '% (stop_time - start_time))
        return res
    return foo

@timmer        # my_max = timmer(my_max)
def my_max(x,y):
    res = x if x > y else y
    return res

res = my_max(2, 3)        #foo(2, 3)
print(res)
  1. 有参装饰器
def auth2(auth_type):
    def auth(func):
        def foo(*args,**kwargs):
            name = input('username: ').strip()
            passwd = input('passwd:')
            if auth_type == 'sql':
                if name == 'liuyang' and passwd == '123':
                    print('auth successful')
                    res = func(*args,**kwargs)
                    return res
                else:
                    print('auth error')
            else:
                print('还没学会')
        return foo
    return auth

@auth2(auth_type = 'sql')        #index = auth(index)
def index():
    print('welcome to index page')

index()        #foo()

三. 装饰器补充

  1. 函数加多个无参装饰器
@ccc
@bbb
@aaa
def func():
    pass

func=ccc(bbb(aaa(func))) 
  1. 函数加多个有参装饰器
@ccc('c')
@bbb('b')
@aaa('a')
def func():
    pass

func=ccc('c')(bbb('b')(aaa('a')(func)))

作业

今日总结

  1. 待整理

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">

原文地址:https://www.cnblogs.com/sama/p/7825401.html