Python 学习之路 - 装饰器

装饰器

装饰器也是函数,用于被装饰函数执行时,增加被装饰函数的功能。

 1 def decor(func):
 2     def warpper(*args,**kwargs):
 3         print("Welcome!")
 4         func(*args,**kwargs)
 5         print("*-------------*")
 6     return warpper
 7 
 8 
 9 @decor
10 def simple(name):
11     print(name)
12 
13 simple("ChangDu")
import time

def timmer(func):
    def warpper(*args,**kwargs):
        start_time=time.time()
        func(*args,**kwargs)
        stop_time=time.time()
        print("The running time:%s"%(stop_time-start_time))
    return warpper

# @ + 函数名
# 1. 自动执行timmer函数并将下面的函数名test1当做参数传递
# 2. 将timmer函数的返回值重新赋值给test1
@timmer #test1=timmer(test1)
def test1(name,ss):#一旦一个函数被装饰,这个函数就会被赋值成装饰函数的内层函数
    time.sleep(3)
    print("test")
    print(name,ss)

test1("amy",ss="uu")
被装饰函数的不同参数传给装饰器
db_user_name,db_password= "amy" , "123"

def auth(func):
    print("----",func)
    def warpper(*args,**kwargs):
        user_name=input("UserName:").strip()
        password=input("Password:").strip()
        if db_user_name==user_name and db_password==password:
            r = func()
            print("hhhh")
            return r
        else:
            print("Error")
    return warpper



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

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

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


index()
print(home())
bbs()
装饰器返回被装饰函数执行后的值
name,password="amy","123"
def auth(way):
    def outer(func):
        def wrapper(*args,**kwargs):
            if way == "local":
                user_name=input("UserName:").strip()
                user_password=input("Password:").strip()
                if user_name==name and user_password==password:
                    print("Welcome------local")
                    r=func()
                    print("End")
                    return r
                else:
                    print("Error")
            elif way == "other":
                print("forget it-----other")
                r = func()
                return r
        return wrapper
    return outer


def index():
    print("Welcome to index")


@auth(way="local")
def home():
    print("Welcome to home")
    return True


@auth(way="other")
def bbs():
    print("Welcome to bbs")

index()
print(home())
bbs()
三层装饰器
def outer(func):
    def warpper(*args,**kwargs):
        print("1")
        r = func(*args,**kwargs)
        return r
    return warpper


def outer2(func):
    def warpper(*args,**kwargs):
        print("2")
        r = func(*args,**kwargs)
        return r
    return warpper

@outer
@outer2
def f1():
    print("test")

f1()
多个装饰器装饰一个函数

 

posted @ 2017-03-11 14:48  耕耘的小白  阅读(134)  评论(0编辑  收藏  举报