初学Python-day12 装饰器函数
2024-09-05 21:11:43
装饰器
1.概念
本质就是一个Python函数,其他函数在本身不变的情况下去增加额外的功能,装饰器的返回值是一个函数。
常用的场景:插入日志,事务处理,缓存,权限校验等。
2.普通函数回顾
1 def speak():
2 print('hello world')
3
4 say = speak
5 say()
3.函数的嵌套
1 def test1():
2 def test2():
3 print('test2')
4 def test3():
5 print('test3')
6 return test2
7 test2 = test1()
8 test2()
4.函数作为参数传递
1 def fun1(arg):
2 def test1():
3 print('---')
4 arg()
5 print('---')
6 return test1
7
8 def say():
9 print('hello world!')
10
11 test1 = fun1(say)
12 test1()
5.装饰器
1 def fun1(arg):
2 def test1():
3 print('=========')
4 arg()
5 print('=========')
6 return True
7 return test1
8
9
10 @fun1
11 def say():
12 print('hello world!')
13
14 say()
15 print(say.__name__)
6.带参数的装饰器
如果需要给装饰器传入参数,则在嵌套一层函数即可
1 from datetime import datetime
2
3
4 def log(text):
5 def decorator(fun1):
6 def warrper(*args, **kwargs):
7 print(text, fun1.__name__)
8 return fun1(*args, **kwargs)
9 return warrper
10 return decorator
11
12
13 @log('text')
14 def now():
15 print(datetime.now())
16
17 now()
18 print(now.__name__)
7.偏函数
--int函数
将字符串中的数值转换为十进制
1 print(int('10'))
2 print(int('10', base=2))
最新文章
- android实现第三方登录之QQ登录
- sql,插入最大值加1
- UVA 10269 Adventure of Super Mario
- UIViewAdditions(一个非常方便的工具类用它)
- iis服务器上面使用百度编辑器ueidtor提示“找不到临时文件”需要给window/temp修改权限
- 201521123047 《Java程序设计》第4周学习总结
- java web后台工作原理
- CRM系统设计方案
- [LeetCode] 78. Subsets tag: backtracking
- create-react-app 搭建的项目中,让 antd 通过侧边栏导航 Menu 的 Menu.Item 控制 Content 部分的变化
- 第01章:MongoDB简介
- Windows XP with SP3大客户免激活日文版
- jsp页面查询的数据导出到excel
- springboot 针对jackson是自动化配置
- 【bzoj4888】: [Tjoi2017]异或和 BIT-乱搞
- easy-ui grid里的toobar按钮隐藏与显示
- 极光推送能获取 registrationId,但是接收不到通知 - iOS
- Angular ui-route的用法
- 电阻 (resistance)
- [转] 重定向 CORS 跨域请求
热门文章
- thrift的介绍及其使用
- vue-admin-element 页面跳转
- [第十三篇]——Docker Compose之Spring Cloud直播商城 b2b2c电子商务技术总结
- 使用 elementUI 的表单进行查询,表单中只有一个文本框时,回车会自动触发表单的提交事件,导致页面的刷新。
- 洛谷P1309——瑞士轮(归并排序)
- POJ 2509 Peter's smokes(Peter的香烟)
- 开源物联网平台(Thingsboard)-编译
- vscode 本地启动配置
- 『Python』matplotlib实现动画效果
- 「含源码」关于NXP IMX8 Mini的图形开发指南(GPU)案例分享!