Python---装饰器详解

2017-10-24  本文已影响29人  coderST

定义:

本质上是一个函数。作用是用来装饰另一个函数(即被装饰函数),给被装饰函数添加功能。前提是不能改变被装饰函数的源代码和调用方式。这样的一个函数称之为装饰器。

解析:

下面我们话不多说,直接用代码说明。下面是一个函数。

1 def add():
2     b=1+2
3     print(b)
4
5 add()
程序输出:
————————

3

————————
#原函数
def add():
    a=1+2
    print(a)  
#装饰器
def decorator(func):
    def warpper():
        print("1+2的结果是:")
        func()
    return warpper
#注意此句   
add=decorator(add)
#调用函数
add()

程序输出:

——————————

1+2的结果是:

3

——————————
#装饰器
def decorator(func):
    def warpper():
        print("1+2的结果是:")
        func()
    return warpper

#add=decorator(add)
#原函数
@decorator#换成@符号
def add():
    a=1+2
    print(a)
#调用函数
add()

在被装饰函数前面直接加上“@xxx”(xxx为装饰器函数名)即可

被装饰函数有参数怎么办?

def decorator(func):
    def warpper(*args,**kwargs):
        print("相加的结果是:")
        func(*args,**kwargs)
    return warpper

@decorator
def add(x,y):
    a=x+y
    print(a)

add(2,3)

程序输出:

——————————————————
相加的结果是:
5
——————————————————

如上,我们给包装函数加上接收参数,然后传给func()函数就行了。这样不管被装饰函数有怎样的参数都不怕了。

下面写一个页面验证的装饰器。

def index():
    print("welcome to the index page")
def home():
    print("welcome to the home page")
def bbs():
    print("welcome to the bbs page")
    return "I am the return contents"
username,passwd="jack","abc123"#模拟一个已登录用户
def decorator(func):
    def warpper(*args,**kwargs):
        Username=input("Username:").strip()
        password=input("Password:").strip()
        if username==Username and passwd==password:
            print("Authenticate Success!")
            func(*args,**kwargs)
        else:
            exit("Username or password is invalid!")
    return warpper

def index():
    print("welcome to the index page")
@decorator
def home():
    print("welcome to the home page")
@decorator
def bbs():
    print("welcome to the bbs page")
    return "I am the return contents"

index()
home()
bbs()

程序结果:

————————

welcome to the index page    #index页面未验证直接可以登入
Username:jack
Password:abc123
Authenticate Success!           #登录的而情形
welcome to the home page
Username:jack                      #密码或用户名错误的情形
Password:123
Username or password is invalid!
————————
————————

welcome to the index page
Username:jack
Password:abc123
Authenticate Success!
welcome to the home page
Username:jack
Password:abc123
Authenticate Success!
welcome to the bbs page
None                              #返回值能么成None了???

————————
username,passwd="jack","abc123"#模拟一个已登录用户
def decorator(func):
    def warpper(*args,**kwargs):
        Username=input("Username:").strip()
        password=input("Password:").strip()
        if username==Username and passwd==password:
            print("Authenticate Success!")
           return func(*args,**kwargs)#在这里加一个return就行了
        else:
            exit("Username or password is invalid!")
    return warpper

def index():
    print("welcome to the index page")
@decorator
def home():
    print("welcome to the home page")
@decorator
def bbs():
    print("welcome to the bbs page")
    return "I am the return contents"

index()
home()
bbs()
————————

welcome to the index page
Username:jack
Password:abc123
Authenticate Success!
welcome to the home page
Username:jack
Password:abc123
Authenticate Success!
welcome to the bbs page
I am the return contents   #bbs()的返回值得到了正确的返回

——-——————

好了,返回值的问题解决了.

既然装饰器是一个函数,那装饰器可以有参数吗?

username,passwd="jack","abc123"#模拟一个已登录用户
def decorator(auth_type):
    def out_warpper(func):
        def warpper(*args,**kwargs):
            Username=input("Username:").strip()
            password=input("Password:").strip()
            if auth_type=="local":
                if username==Username and passwd==password:
                    print("Authenticate Success!")
                    return func(*args,**kwargs)
                else:
                    exit("Username or password is invalid!")
            elif auth_type=="unlocal":
                print("HERE IS UNLOCAL AUTHENTICATE WAYS")
        return warpper
    return out_warpper

def index():
    print("welcome to the index page")
@decorator(auth_type="local")
def home():
    print("welcome to the home page")
@decorator(auth_type="unlocal")
def bbs():
    print("welcome to the bbs page")
    return "I am the return contents"

index()
home()
bbs()

输出:

————————

welcome to the index page
Username:jack
Password:abc123
Authenticate Success!
welcome to the home page
Username:jack
Password:abc123
HERE IS UNLOCAL AUTHENTICATE WAYS

————————

原文链接:http://www.cnblogs.com/Akkbe-chao/p/6980332.html

上一篇下一篇

猜你喜欢

热点阅读