python闭包函数&装饰器
2022/1/20 20:17:46
本文主要是介绍python闭包函数&装饰器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、函数引用
-
函数可以被引用
-
函数可以被赋值给一个变量
def hogwarts(): print("hogwarts") # hogwarts() # 函数调用 print(hogwarts) print('----------------') harry = hogwarts # 把函数对象赋值给一个变量 print(harry) print('----------------') harry() # 引用函数
二、闭包函数
-
闭包的内部函数中,对外部作用域的变量进行引用
-
闭包无法修改外部函数的局部变量
-
闭包可以保存当前的运行环境
def student_grade(grade): # 闭包无法修改外部函数的局部变量 grade = '22' print('外函数年级:', grade) def output_student(name, gender): grade = '11' print('内函数年级为:', grade) # print(f"霍格沃兹测试学社开学啦!" # f"学生的名称是{name}," # f"性别是{gender}年级是{grade}") return output_student student = student_grade(1) student("罗恩", "男") student("哈利", "男") student("赫敏", "女")
三、python装饰器
-
行业需求: 涉及 Python 技术栈,面试常见题
-
使用需求: 优化代码的可读性,可维护性
四、装饰器示例
-
函数体开始执行与结束执行的时候分别添加打印信息
""" 装饰器示例 函数体开始执行与结束执行的时候分别添加打印信息 """ def hogwarts(): print("霍格沃兹测试学社") def hogwarts2(): print("霍格沃兹测试学社2") # 把中间的执行函数,使用参数代替 def function_tips(func): print("函数开始执行") # 不在写死的任何的一个函数,而是任意外部传入的函数 func() print('函数结束执行') # 函数对象 function_tips(hogwarts) function_tips(hogwarts2)
六、装饰器带参数
def timer(func): # 如果被装饰函数有参数,那么需要在内函数加形参以及在函数参数调用的时候添加参数信息 # 如果写死一个参数,但是无法确定被装饰函数的参数数量,这种写法就不行,会报错 # 解决方法:把两个地方的参数全部换成不定长参数 def inner(*args, **kwargs): # 获取当前时间 start_time = datetime.datetime.now() func(*args, **kwargs) end_time = datetime.datetime.now() print(f"函数的执行时间{end_time - start_time}") return inner @timer def hogwarts(name, age): print("霍格沃兹测试学社", name, age) hogwarts('Tom', 4) @timer def hogwarts2(name, age, sex): print("霍格沃兹测试学社2", name, age, sex) hogwarts2('jack', 11, 'man')
这篇关于python闭包函数&装饰器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python