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 = '漂亮的小裙子' ...
随机推荐
- storm的并发
1 storm并行的基本概念 storm集群中的一个机器可以运行一个或者多个worker,对应于一个或者多个topologies. 1个worker进程运行1个或多个excutor线程.每个worke ...
- islands打炉石传说<DP>
islands最近在完一款游戏"炉石传说",又名"魔兽英雄传".炉石传说是一款卡牌类对战的游戏.游戏是2人对战,总的来说,里面的卡牌分成2类,一类是法术牌,另一 ...
- JAVA Timer定时器使用方法(二)
JAVA Timer 定时器测试 MyTask.java:package com.timer; import java.text.SimpleDateFormat;import java.util. ...
- (转)如何向map和reduce脚本传递参数
[MapReduce] 如何向map和reduce脚本传递参数,加载文件和目录 分类: hadoop2014-04-28 21:30 1553人阅读 评论(0) 收藏 举报 hadoop 本文主要讲解 ...
- photosho 等距复制或旋转复制
选区是不可以复制的,不过可以用这个方法:1.新建图层,任意绘制一个图形2.ctrl+j复制一层,ctrl+T 切换到变形工具,移动或变形该图形后enter.3.按Alt+Shift+ctrl+T.4. ...
- Android音频系统之AudioFlinger(二)
1.1.1 音频设备的管理 虽然AudioFlinger实体已经成功创建并初始化,但到目前为止它还是一块静态的内存空间,没有涉及到具体的工作. 从职能分布上来讲,AudioPolicyService是 ...
- PAT (Advanced Level) 1028. List Sorting (25)
时间卡的比较死,用string会超时. #include<cstdio> #include<cstring> #include<cmath> #include< ...
- Bootstrap Table的使用
前言:BootstrapTable基于Bootstrap,Bootstrap基于jquery,所以需要引入jquery后再引入bootstrap. <link href="${ctx} ...
- iframe与父页面的js通信
1.父页面调用iframe中的函数: document.getElementById('myframe').contentWidow.fun1(); 2.在iframe中调用父页面中的函数: wind ...
- Deep learning:三十八(Stacked CNN简单介绍)
http://www.cnblogs.com/tornadomeet/archive/2013/05/05/3061457.html 前言: 本节主要是来简单介绍下stacked CNN(深度卷积网络 ...