Python装饰器学习(九步入门)
这是在Python学习小组上介绍的内容,现学现卖、多练习是好的学习方式。
第一步:最简单的函数,准备附加额外功能
|
1
2
3
4
5
6
7
8
|
# -*- coding:gbk -*-'''示例1: 最简单的函数,表示调用了两次'''def myfunc(): print("myfunc() called.")myfunc()myfunc() |
第二步:使用装饰函数在函数执行前和执行后分别附加额外功能
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
# -*- coding:gbk -*-'''示例2: 替换函数(装饰)装饰函数的参数是被装饰的函数对象,返回原函数对象装饰的实质语句: myfunc = deco(myfunc)'''def deco(func): print("before myfunc() called.") func() print(" after myfunc() called.") return funcdef myfunc(): print(" myfunc() called.")myfunc = deco(myfunc)myfunc()myfunc() |
第三步:使用语法糖@来装饰函数
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# -*- coding:gbk -*-'''示例3: 使用语法糖@来装饰函数,相当于“myfunc = deco(myfunc)”但发现新函数只在第一次被调用,且原函数多调用了一次'''def deco(func): print("before myfunc() called.") func() print(" after myfunc() called.") return func@decodef myfunc(): print(" myfunc() called.")myfunc()myfunc() |
第四步:使用内嵌包装函数来确保每次新函数都被调用
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# -*- coding:gbk -*-'''示例4: 使用内嵌包装函数来确保每次新函数都被调用,内嵌包装函数的形参和返回值与原函数相同,装饰函数返回内嵌包装函数对象'''def deco(func): def _deco(): print("before myfunc() called.") func() print(" after myfunc() called.") # 不需要返回func,实际上应返回原函数的返回值 return _deco@decodef myfunc(): print(" myfunc() called.") return 'ok'myfunc()myfunc() |
第五步:对带参数的函数进行装饰
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# -*- coding:gbk -*-'''示例5: 对带参数的函数进行装饰,内嵌包装函数的形参和返回值与原函数相同,装饰函数返回内嵌包装函数对象'''def deco(func): def _deco(a, b): print("before myfunc() called.") ret = func(a, b) print(" after myfunc() called. result: %s" % ret) return ret return _deco@decodef myfunc(a, b): print(" myfunc(%s,%s) called." % (a, b)) return a + bmyfunc(1, 2)myfunc(3, 4) |
第六步:对参数数量不确定的函数进行装饰
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
# -*- coding:gbk -*-'''示例6: 对参数数量不确定的函数进行装饰,参数用(*args, **kwargs),自动适应变参和命名参数'''def deco(func): def _deco(*args, **kwargs): print("before %s called." % func.__name__) ret = func(*args, **kwargs) print(" after %s called. result: %s" % (func.__name__, ret)) return ret return _deco@decodef myfunc(a, b): print(" myfunc(%s,%s) called." % (a, b)) return a+b@decodef myfunc2(a, b, c): print(" myfunc2(%s,%s,%s) called." % (a, b, c)) return a+b+cmyfunc(1, 2)myfunc(3, 4)myfunc2(1, 2, 3)myfunc2(3, 4, 5) |
第七步:让装饰器带参数
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
# -*- coding:gbk -*-'''示例7: 在示例4的基础上,让装饰器带参数,和上一示例相比在外层多了一层包装。装饰函数名实际上应更有意义些'''def deco(arg): def _deco(func): def __deco(): print("before %s called [%s]." % (func.__name__, arg)) func() print(" after %s called [%s]." % (func.__name__, arg)) return __deco return _deco@deco("mymodule")def myfunc(): print(" myfunc() called.")@deco("module2")def myfunc2(): print(" myfunc2() called.")myfunc()myfunc2() |
第八步:让装饰器带 类 参数
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
# -*- coding:gbk -*-'''示例8: 装饰器带类参数'''class locker: def __init__(self): print("locker.__init__() should be not called.") @staticmethod def acquire(): print("locker.acquire() called.(这是静态方法)") @staticmethod def release(): print(" locker.release() called.(不需要对象实例)")def deco(cls): '''cls 必须实现acquire和release静态方法''' def _deco(func): def __deco(): print("before %s called [%s]." % (func.__name__, cls)) cls.acquire() try: return func() finally: cls.release() return __deco return _deco@deco(locker)def myfunc(): print(" myfunc() called.")myfunc()myfunc() |
第九步:装饰器带类参数,并分拆公共类到其他py文件中,同时演示了对一个函数应用多个装饰器
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
# -*- coding:gbk -*-'''mylocker.py: 公共类 for 示例9.py'''class mylocker: def __init__(self): print("mylocker.__init__() called.") @staticmethod def acquire(): print("mylocker.acquire() called.") @staticmethod def unlock(): print(" mylocker.unlock() called.")class lockerex(mylocker): @staticmethod def acquire(): print("lockerex.acquire() called.") @staticmethod def unlock(): print(" lockerex.unlock() called.")def lockhelper(cls): '''cls 必须实现acquire和release静态方法''' def _deco(func): def __deco(*args, **kwargs): print("before %s called." % func.__name__) cls.acquire() try: return func(*args, **kwargs) finally: cls.unlock() return __deco return _deco |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
# -*- coding:gbk -*-'''示例9: 装饰器带类参数,并分拆公共类到其他py文件中同时演示了对一个函数应用多个装饰器'''from mylocker import *class example: @lockhelper(mylocker) def myfunc(self): print(" myfunc() called.") @lockhelper(mylocker) @lockhelper(lockerex) def myfunc2(self, a, b): print(" myfunc2() called.") return a + bif __name__=="__main__": a = example() a.myfunc() print(a.myfunc()) print(a.myfunc2(1, 2)) print(a.myfunc2(3, 4)) |
Python装饰器学习(九步入门)的更多相关文章
- Python 装饰器学习
Python装饰器学习(九步入门) 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 1 2 3 4 5 6 7 8 # -*- c ...
- Python装饰器学习
Python装饰器学习(九步入门) 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方式. 第一步:最简单的函数,准备附加额外功能 ? 1 2 3 4 5 6 7 8 # -*- ...
- (转载)Python装饰器学习
转载出处:http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html 这是在Python学习小组上介绍的内容,现学现卖.多练习是好的学习方 ...
- Python 装饰器学习心得
最近打算重新开始记录自己的学习过程,于是就捡起被自己废弃了一年多的博客.这篇学习笔记主要是记录近来看的有关Python装饰器的东西. 0. 什么是装饰器? 本质上来说,装饰器其实就是一个特殊功能的函数 ...
- python 装饰器学习(decorator)
最近看到有个装饰器的例子,没看懂, #!/usr/bin/python class decorator(object): def __init__(self,f): print "initi ...
- python装饰器学习详解-函数部分
本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理 最近阅读<流畅的python>看见其用函数写装饰器部分写的很好,想写一些自己的读书笔记. ...
- Python 装饰器学习以及实际使用场景实践
前言 前几天在看Flask框架,对于非常神奇的@语法,不是非常的理解,回来补装饰器的功课.阅读很多的关于装饰器的文章,自己整理一下,适合自己的思路的方法和例子,与大家分享. app = Flask(_ ...
- python 装饰器 第十一步:多层装饰器的嵌套
#第十一步:多层装饰器的嵌套 #装饰器1 def kuozhan1(func): #定义装饰之后的函数 def neweat1(): # 扩展功能1 print('1-----饭前洗手') # 调用基 ...
- python 装饰器 第十步:装饰器来装饰器一个类
第十步:装饰器来装饰一个类 def kuozhan(cls): print(cls) #声明一个类并且返回 def newHuman(): # 扩展类的功能1 cls.cloth = '漂亮的小裙子' ...
随机推荐
- emacs format
格式化源码是很常见的需求,emacs有个indent-region函数用于格式化选定的代码,前提是你处在某个非text mode下,如c-mode或者java-mode之类.如果要格式化整个文件,你需 ...
- call_compile.sql
set echo off prompt prompt ========================================================================= ...
- OpenGL学习--------颜色的选择
OpenGL支持两种颜色模式:一种是RGBA,一种是颜色索引模式.无论哪种颜色模式,计算机都必须为每一个像素保存一些数据.不同的是,RGBA模式中,数据直接就代表了颜色:而颜色索引模式中,数据代表的是 ...
- CentOS 6.5配置mysql
启动mysql service mysqld start 给root账号设置密码 mysqladmin -u root password '
- 安卓EditText按钮
main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:and ...
- 关于flex4 list 高度适应内容
Flex 4: Setting Spark List height to its content height How to set a Spark List height to the height ...
- css中margin重叠和一些相关概念(包含块containing block、块级格式化上下文BFC、不可替换元素 non-replaced element、匿名盒Anonymous boxes )
平时在工作中,总是有一些元素之间的边距与设定的边距好像不一致的情况,一直没明白为什么,最近仔细研究了一下,发现里面有学问:垂直元素之间的margin有有互相重叠的情况:新建一个BFC后,会阻止元素与外 ...
- glibc
http://www.cnblogs.com/vipzrx/p/3599506.html 原因 wheezy是2.13,编译android4.4 需要2.14的,报错如下: rebuilts/gcc/ ...
- [iOS]C语言技术视频-02-程序分支结构(if...else)
下载地址: 链接: http://pan.baidu.com/s/1dREc2 密码: egbt
- dependency injection(2)
https://segmentfault.com/a/1190000002424023