闭包和装饰器

python 复制代码
#闭包的作用
#全局变量有被修改的风险,代码在命名空间上不够干净整洁
#第一种,不使用闭包的场景
account_amount=0
def atm(num,deposit=True):
    global account_amount
    if deposit:
        account_amount+=num
        print(f"存款:+{num},账户余额{account_amount}")
    else:
        account_amount-=num
        print(f"存款:-{num},账户余额{account_amount}")
atm(300) #存款:300,账户余额300
atm(300) #存款:300,账户余额600
atm(100,False) #存款:100,账户余额500
#从上面可以看到全局变量在被不断的修改,同时,代码也不够干净

#使用闭包的写法见如下,这种就不会有全局变量了,这种就是闭包了
def account_create(initial_amount=0):
    def atm(num,deposit=True):
        nonlocal initial_amount #这条句子定义后,后续可以在修改变量
        if deposit:
            initial_amount+=num
            print(f"存款+{num},账户余额{initial_amount}")
        else:
            initial_amount-=num
            print(f"存款-{num},账户余额{initial_amount}")
    return atm
fn=account_create()
fn(100)  #存款+100,账户余额100
fn(200)  #存款+200,账户余额300

#闭包的优点 无需要定义全局变量就可以通过函数,持续的访问修改某个值,闭包使用的变量在于函数内,难被错误的调用修改
#缺点,由于内部持续引用外包函数的值,所以会导致内存空间不足,一直占用内存
相关推荐
belldeep2 小时前
如何阅读、学习 Tcc (Tiny C Compiler) 源代码?如何解析 Tcc 源代码?
c语言·开发语言
LuckyTHP2 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
mahuifa4 小时前
(7)python开发经验
python·qt·pyside6·开发经验
学地理的小胖砸5 小时前
【Python 操作 MySQL 数据库】
数据库·python·mysql
安迪小宝5 小时前
6 任务路由与负载均衡
运维·python·celery
Blossom.1185 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算
da-peng-song5 小时前
ArcGIS Desktop使用入门(二)常用工具条——数据框工具(旋转视图)
开发语言·javascript·arcgis
galaxy_strive5 小时前
qtc++ qdebug日志生成
开发语言·c++·qt
TNTLWT5 小时前
Qt功能区:简介与安装
开发语言·qt
lisw055 小时前
Python高级进阶:Vim与Vi使用指南
python·vim·excel