
python入门开发笔记之函数进阶
局部(Locals): 包含函数内的局部变量和参数。 外部嵌套函数的局部(Enclosing Function's Locals): 对于嵌套函数而言,其外部函数的局部变量范围。 全局(Globals): 包含全局变量,函数定义所在模块的名字空间。 内置(Builtins): 包含内置模块的名字空间。
发布日期:2025-05-13 01:29:49
浏览次数:2
分类:精选文章
本文共 4299 字,大约阅读时间需要 14 分钟。
Python 函数与装饰器实践
一、函数名称空间
在 Python 中,函数内部的变量、参数等都是存放在名称空间中的。名称空间分为局部(locals)、全局(globals)和内置(builtins)三个层次。不同变量的作用域由它们所在的命名空间决定。
作用域查找顺序
Python 的命名查找遵循 LEGB 原则:
例如,在下面的代码中,n
的值会是多少?
level = 'L0'n = 22def func(): level = 'L1' n = 33 print(locals()) def outer(): n = 44 level = 'L2' print(locals(), n) # 此处打印的 n 是多少? def inner(): level = 'L3' print(locals(), n) # 此外打印的 n 是多少? inner() outer()func()
闭包
闭包是指在函数外定义的函数能够记住它外部函数的变量和状态。例如:
def outer(): name = 'alex' def inner(): print("在 inner 里打印外层函数的变量", name) return innerf = outer()f()
装饰器
装饰器是一种高阶函数,用来装饰其他函数,添加额外功能。通过在函数定义上使用 @
符号,可以在不修改原函数的情况下扩展其功能。
例如,用于添加认证功能的装饰器:
def login(func): def inner(*args, **kwargs): _username = "alex" _password = "abc!23" global user_status if user_status == False: username = input("user:") password = input("pasword:") if username == _username and password == _password: print("welcome login....") user_status = True else: print("wrong username or password!") if user_status == True: return func(*args, **kwargs) return inneruser_status = Falsedef home(): print("---首页----")@logindef america(): print("----欧美专区----")def japan(): print("----日韩专区----")@logindef henan(): print("----河南专区----")home()america()henan()
练习题
一、编写三个函数,每个函数执行的时间不同
import timedef sleepy(): time.sleep(2) print("睡了2秒")def sleepy2(): time.sleep(4) print("睡了4秒")def sleepy3(): time.sleep(6) print("睡了6秒")
二、编写装饰器,为每个函数加上统计运行时间的功能
import timedef decorator(func): def inner(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"函数执行时间:{end - start} 秒") return result return inner@decoratordef sleepy(): time.sleep(2) print("睡了2秒")@decoratordef sleepy2(): time.sleep(4) print("睡了4秒")@decoratordef sleepy3(): time.sleep(6) print("睡了6秒")
三、编写装饰器,为函数加上认证的功能
def login(func): def inner(*args, **kwargs): _username = "alex" _password = "abc!23" global user_status if user_status == False: username = input("user:") password = input("pasword:") if username == _username and password == _password: print("welcome login....") user_status = True else: print("wrong username or password!") if user_status == True: return func(*args, **kwargs) return inneruser_status = Falsedef home(): print("---首页----")@logindef america(): print("----欧美专区----")def japan(): print("----日韩专区----")@logindef henan(): print("----河南专区----")home()america()henan()
四、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
import osdef login(func): def inner(*args, **kwargs): auth_file = "auth.txt" try: with open(auth_file, 'r') as f: data = f.read() user_info = eval(data) _username = user_info['name'] _password = user_info['password'] global user_status if user_status == False: username = input("user:") password = input("pasword:") if username == _username and password == _password: print("welcome login....") user_status = True else: print("wrong username or password!") if user_status == True: return func(*args, **kwargs) except Exception as e: print(f"读取认证文件失败:{e}") return return inneruser_status = Falsedef home(): print("---首页----")@logindef america(): print("----欧美专区----")def japan(): print("----日韩专区----")@logindef henan(): print("----河南专区----")home()america()henan()
通过以上练习,可以更深入地理解函数命名空间、闭包和装饰器的原理及其应用。
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2025年04月19日 15时02分33秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
LAMP与LNMP架构详解
2025-04-04
LAMP网站平台搭建
2025-04-04
LangChain:链接语言与智能的未来
2025-04-04
LangSmith的简单介绍
2025-04-04
laradock 安装使用 kafka
2025-04-04
laravel 5.3 给容器传参
2025-04-04
laravel 5.3用户认证--默认的用户表数据迁移
2025-04-04
laravel 5.5 -- Eloquent 模型关联
2025-04-04
laravel 5.5 -- Homestead
2025-04-04
laravel mix
2025-04-04
laravel on duplicate key update
2025-04-04
Laravel Passport
2025-04-04
Laravel RESTful API 开发框架指南
2025-04-04
laravel 之 Eloquent 模型修改器和序列化
2025-04-04
Laravel 使用 - artisan schedule使用
2025-04-04
Laravel 使用rdkafka
2025-04-04
Laravel 多环境配置
2025-04-04
laravel 学习之第一章
2025-04-04
laravel 学习之第二章
2025-04-04