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 = '漂亮的小裙子' ...
随机推荐
- laytpl.js 模板使用记录
{{# for(var j = 0, len = d.length; j < len; j++){ }} <div class="pure-u-1-5 pure-u-sm-1 p ...
- delphi第2节
- foo bar的意思
有些朋友问:foo, bar是什么意思, 为什么C++书籍中老见到这个词. 我google了一下, 发现没有很好的中文答案.这个问题,在维基百科上有很好的回答.在这里翻译给大家. 译文: 术语foob ...
- CentOS 修改Mysql的root密码
1.知道密码 第一次登陆(无密码) mysqladmin -u root password NEWPASSWORD 修改过密码 mysqladmin -u root -p 'oldpassword' ...
- UIApplication,UIWindow,UIViewController,UIView(layer)
转载自:http://www.cnblogs.com/iCocos/p/4684749.html UIApplication,UIWindow,UIViewController,UIView(laye ...
- copy ,abs,includes 3个函数
copy: Copy函数原型:标头: <algorithm> OutputIterator copy( InputIterator begin, InputIterator end, o ...
- zencart里常用 SQL
1.如何替换某个字段的一些字符 如我把products表的products_image字段中包含2011的字符替换成Zencart2012update `products` set `products ...
- Entity Framework Power Tools Beta 3
http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d/ PM> Install-P ...
- iOS中4种判断网络请求的方式(系统状态栏、AFNetworking、Reachability、自定义)
iOS 实时判断网络状态 方法一:利用系统状态栏判断网络状态 // 状态栏是由当前app控制的,首先获取当前app UIApplication *app = [UIApplication shared ...
- latex题注(caption)位置
http://anything-is-ok.blog.163.com/blog/static/205720233201301634053760/ 我们以插入图片为例来说明latex中将题注(capti ...