python学习之闭包与装饰器

一、闭包

闭包允许一个函数访问并操作函数外部的变量(即父级作用域中的变量),即使在该函数外部执行。

特性:

(1)外部函数嵌套内部函数。

(2)外部函数可以返回内部函数。

(3)内部函数可以访问外部函数的局部变量。

def out():
    print("我是外层")
    n = 10

    def ins():
        print("我是内层")
        nonlocal n
        n += 30
        print(n)
    return ins



out()
i = out()
i()

 

二、装饰器

装饰器(Decorator)是Python中一种强大的函数或类修饰机制,它允许开发者在不修改原始函数或类代码的情况下,对其进行功能扩展或修改。装饰器基于函数式编程的概念,通过将函数作为参数传递给另一个函数,并返回一个新的函数来实现。

概念:一个闭包就是一个函数+在创建这个函数时可以访问的变量

定义:装饰器本质上是一个Python函数或类,它接收一个函数或类作为参数,并返回一个新的函数或类对象。

实现:闭包+@语法

@decorator  
def func():  
    pass

三、装饰器案例

1.时间开销



def time_cost(f):

    def calc():

        start = time.time()

        f()

        print(f"结束执行: {f.__name__} 消耗时间 {time.time()-start}")





    return calc



@time_cost

def fun1():

    datas.sort()

    print(datas)



# fun1 = time_cost(fun1)

fun1()



# fun1()





@time_cost

def fun2():

    new_datas = sorted(datas_copy)

    print(new_datas)





# fun2 = time_cost(fun2)

fun2()

# fun2()

2.权限校验

# 当前登录用户

user = None





def login_required(f):

    def check():

        global user

        if user:

            f()

        else:

            while True:

                username = input("输入用户名")

                password = input("输入密码")

                if username == "admin" and password == "123456":

                    user = "admin"

                    f()

                    break

                else:

                    print(f"用户名密码错误")



    return check





def index():

    print(f"我是首页")





@login_required

def center():

    print(f"我是个人中心")





@login_required

def cart():

    print(f"我是购物车")





# index()

# center()

# cart()



index()



# center = login_required(center)

center()



# cart = login_required(cart)

cart()

  • 34
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值