装饰器

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))

最新文章

  1. android实现第三方登录之QQ登录
  2. sql,插入最大值加1
  3. UVA 10269 Adventure of Super Mario
  4. UIViewAdditions(一个非常方便的工具类用它)
  5. iis服务器上面使用百度编辑器ueidtor提示“找不到临时文件”需要给window/temp修改权限
  6. 201521123047 《Java程序设计》第4周学习总结
  7. java web后台工作原理
  8. CRM系统设计方案
  9. [LeetCode] 78. Subsets tag: backtracking
  10. create-react-app 搭建的项目中,让 antd 通过侧边栏导航 Menu 的 Menu.Item 控制 Content 部分的变化
  11. 第01章:MongoDB简介
  12. Windows XP with SP3大客户免激活日文版
  13. jsp页面查询的数据导出到excel
  14. springboot 针对jackson是自动化配置
  15. 【bzoj4888】: [Tjoi2017]异或和 BIT-乱搞
  16. easy-ui grid里的toobar按钮隐藏与显示
  17. 极光推送能获取 registrationId,但是接收不到通知 - iOS
  18. Angular ui-route的用法
  19. 电阻 (resistance)
  20. [转] 重定向 CORS 跨域请求

热门文章

  1. thrift的介绍及其使用
  2. vue-admin-element 页面跳转
  3. [第十三篇]——Docker Compose之Spring Cloud直播商城 b2b2c电子商务技术总结
  4. 使用 elementUI 的表单进行查询,表单中只有一个文本框时,回车会自动触发表单的提交事件,导致页面的刷新。
  5. 洛谷P1309——瑞士轮(归并排序)
  6. POJ 2509 Peter's smokes(Peter的香烟)
  7. 开源物联网平台(Thingsboard)-编译
  8. vscode 本地启动配置
  9. 『Python』matplotlib实现动画效果
  10. 「含源码」关于NXP IMX8 Mini的图形开发指南(GPU)案例分享!