装饰器

装饰器
1、闭包
关于闭包,即函数定义和函数表达式位于另一个函数的函数体内(嵌套函数)。而且,这些内部函数可以访问它们所在的外部函数中声明的所有局部变量、参数。当其中一个这样的内部函数在包含它们的外部函数之外被调用时,就会形成闭包。也就是说,内部函数会在外部函数返回后被执行。而当这个内部函数执行时,它仍然必需访问其外部函数的局部变量、参数以及其他内部函数。这些局部变量、参数和函数声明(最初时)的值是外部函数返回时的值,但也会受到内部函数的影响
def outer():
    name = 'xu'
    def inner():
        print("在inner里打印外层函数的变量",name)
    return inner # 注意这里只是返回inner的内存地址,并未执行
f = outer() # .inner at 0x1027621e0>
f()  # 相当于执行的是inner()
注意此时outer已经执行完毕,正常情况下outer里的内存都已经释放了,但此时由于闭包的存在,我们却还可以调用inner, 并且inner内部还调用了上一层outer里的name变量。这种粘粘糊糊的现象就是闭包。

闭包的意义:返回的函数对象,不仅仅是一个函数对象,在该函数外还包裹了一层作用域,这使得,该函数无论在何处调用,优先使用自己外层包裹的作用域.
----------此文来源于老男孩(old-boy)-----------------

2、装饰器
def home():
    print("-----------welcome home-----------")
def shop():
    print("-----------welcome shop-----------")
def shopping_car():
    print("-----------welcome shopping_car-----------")
在不改变函数里边的代码和函数调用方式的情况下,为上面的函数新增加一个用户认证功能,此时就需要用到python中的装饰器

account = {
"is_authenticated":False,# 用户登录了就把这个改成True
    "username":"alex", # 假装这是DB里存的用户信息
    "password":"abc123" # 假装这是DB里存的用户信息
}

def login(func):
    def innner():
        if account["is_authenticated"] is False:
            username = input("user:")
            password = input("pasword:")
            if username == account["username"] and password == account["password"]:
                print("welcome login....")
                account["is_authenticated"] = True
            else:
                print("wrong username or password!")
            if account["is_authenticated"] is True:
            func()
    return inner


@login()  #就相当于 home = login(home) home()
def home():
    print("-----------welcome home-----------")


@login()   
def shop():
    print("-----------welcome shop-----------")


@login()
def shopping_car():
    print("-----------welcome shopping_car-----------")


装饰器传参数

def login(func):
    def innner(*args, **kwargs):  # 每个函数的传过来的参数不同,所以要用非固定参数
        if account["is_authenticated"] is False:
            username = input("user:")
            password = input("pasword:")
            if username == account["username"] and password == account["password"]:
                print("welcome login....")
                account["is_authenticated"] = True
            else:
                print("wrong username or password!")
            if account["is_authenticated"] is True:
            func(*args, **kwargs)
    return inner


@login()  #就相当于 home = login(home) home(a)
def home(a):
    print("-----------welcome home-----------")
    print(a)

@login()   
def shop(b):
    print("-----------welcome shop-----------")
    print(b)

@login()
def shopping_car(c):
    print("-----------welcome shopping_car-----------")
    print(c)
原文地址:https://www.cnblogs.com/zrxu/p/11580095.html