Python装饰器入门学习(转载)

前言

转载来源:https://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html
说一说个人理解,第二步和第三步其实并没有完全实现装饰器的作用,只在第一次调用的时候有效,因为装饰器函数返回的还是调用装饰器的函数本身,所以只有第一次生效。在看完第四步时我想在第三步做修改,想以deco代替返回的func,程序报错。原因是因为返回的deco函数和原来的myfunc函数不一致,myfunc函数没有返回值,而deco却返回的一个函数(这个其实只是函数的索引吧,个人理解),然后第四步就能够匹配了。


myfunc = deco(myfunc)装饰器相当于执行这条语句,就相当原来的myfunc函数索引重新指向的deco(func)函数,所以在第四步执行myfunc()时,相当于 deco(myfunc)执行,这就不难理解第三步为什么没有达到装饰器的效果了。


后面应该没有太难理解的,耐心看下去就可以了。

正文

这是在Python学习小组上介绍的内容,现学现卖、多练习是好的学习方式。

第一步:最简单的函数,准备附加额外功能

?
1
2
3
4
5
6
7
8
# -*- coding: UTF-8 -*-
'''示例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: UTF-8 -*-
'''示例2: 替换函数(装饰)
装饰函数的参数是被装饰的函数对象,返回原函数对象
装饰的实质语句: myfunc = deco(myfunc)'''
 
def deco(func):
     print ( "before myfunc() called." )
     func()
     print ( "  after myfunc() called." )
     return func
 
def 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: UTF-8 -*-
'''示例3: 使用语法糖@来装饰函数,相当于“myfunc = deco(myfunc)”
但发现新函数只在第一次被调用,且原函数多调用了一次'''
 
def deco(func):
     print ( "before myfunc() called." )
     func()
     print ( "  after myfunc() called." )
     return func
 
@deco
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
19
# -*- coding: UTF-8 -*-
'''示例4: 使用内嵌包装函数来确保每次新函数都被调用,
内嵌包装函数的形参和返回值与原函数相同,装饰函数返回内嵌包装函数对象'''
 
def deco(func):
     def _deco():
         print ( "before myfunc() called." )
         func()
         print ( "  after myfunc() called." )
         # 不需要返回func,实际上应返回原函数的返回值
     return _deco
 
@deco
def 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: UTF-8 -*-
'''示例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
 
@deco
def myfunc(a, b):
     print ( " myfunc(%s,%s) called." % (a, b))
     return a + b
 
myfunc( 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: UTF-8 -*-
'''示例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
 
@deco
def myfunc(a, b):
     print ( " myfunc(%s,%s) called." % (a, b))
     return a + b
 
@deco
def myfunc2(a, b, c):
     print ( " myfunc2(%s,%s,%s) called." % (a, b, c))
     return a + b + c
 
myfunc( 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: UTF-8 -*-
'''示例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: UTF-8 -*-
'''示例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: UTF-8 -*-
'''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: UTF-8 -*-
'''示例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 + b
 
if __name__ = = "__main__" :
     a = example()
     a.myfunc()
     print (a.myfunc())
     print (a.myfunc2( 1 , 2 ))
     print (a.myfunc2( 3 , 4 ))

下面是参考资料,当初有不少地方没看明白,真正练习后才明白些:

1. Python装饰器学习 http://blog.csdn.net/thy38/article/details/4471421

2. Python装饰器与面向切面编程 http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html

3. Python装饰器的理解 http://apps.hi.baidu.com/share/detail/17572338



更新一下,关于装饰器装饰带有返回值函数的问题,如果自认为不是很了解装饰器,那么请务必仔细的看(转载排版有些问题,点击下链接看原文),文章转载自http://makaidong.com/Akkbe-chao/11621_121627.html>http://makaidong.com/Akkbe-chao/11621_121627.html


————–

Python—装饰器详解

定义:

本质上是一个函数。作用是用来装饰另一个函数(即被装饰函数),给被装饰函数添加功能。前提是不能改变被装饰函数的源代码和调用方式。这样的一个函数称之为装饰器。

解析:

此文来自: 马开东云搜索 转载请注明出处 网址: http://makaidong.com

此文原标题: python装饰器详解 来源网址: http://makaidong.com/Akkbe-chao/11621_121627.html

下面写一个页面验证的装饰器。

大家知道有些网站的一部分页面是要求用户登录之后才可以访问的,比如下面的三个函数(分别代表三个页面):

1 def index():
2     print("welcome to the index page")
3 def home():
4     print("welcome to the home page")
5 def bbs():
6     print("welcome to the bbs page")
7     return "I am the return contents"

假如说现在我们要给home页面和bbs页面加上验证,显然现在更改源代码是不可行的。这个时候我们可以用装饰器,如下:

 1 username,passwd="jack","abc123"#模拟一个已登录用户
 2 def decorator(func):
 3     def warpper(*args,**kwargs):
 4         Username=input("Username:").strip()
 5         password=input("Password:").strip()
 6         if username==Username and passwd==password:
 7             print("Authenticate Success!")
 8             func(*args,**kwargs)
 9         else:
10             exit("Username or password is invalid!")
11     return warpper
12 
13 def index():
14     print("welcome to the index page")
15 @decorator
16 def home():
17     print("welcome to the home page")
18 @decorator
19 def bbs():
20     print("welcome to the bbs page")
21     return "I am the return contents"
22 
23 index()
24 home()
25 bbs()

程序结果:

————————

welcome to the index page    #index页面未验证直接可以登入
Username:jack
Password:abc123
Authenticate Success!           #登录的而情形
welcome to the home page
Username:jack                      #密码或用户名错误的情形
Password:123
Username or password is invalid!
————————

我们注意到bbs()是有返回值的,如果我们把上述代码的最后一句(第25行)改为“print(bbs())”之后再看看他的输出结果:

————————

welcome to the index page
Username:jack
Password:abc123
Authenticate Success!
welcome to the home page
Username:jack
Password:abc123
Authenticate Success!
welcome to the bbs page
None                              #返回值能么成None了???

————————

What happened! bbs()的返回值打印出来竟然是None。怎么会这样?这样的话不就改变了被装饰函数的源代码了吗?怎样才能解决呢?

我们来分析一下:

我们执行bbs函数其实就相当于执行了装饰器里的wrapper函数,仔细分析装饰器发现wrapper函数却没有返回值,所以为了让他可以正确保证被装饰函数的返回值可以正确返回,那么需要对装饰器进行修改:

1 username,passwd="jack","abc123"#模拟一个已登录用户
 2 def decorator(func):
 3     def warpper(*args,**kwargs):
 4         Username=input("Username:").strip()
 5         password=input("Password:").strip()
 6         if username==Username and passwd==password:
 7             print("Authenticate Success!")
 8            return func(*args,**kwargs)#在这里加一个return就行了
 9         else:
10             exit("Username or password is invalid!")
11     return warpper
12 
13 def index():
14     print("welcome to the index page")
15 @decorator
16 def home():
17     print("welcome to the home page")
18 @decorator
19 def bbs():
20     print("welcome to the bbs page")
21     return "I am the return contents"
22 
23 index()
24 home()
25 bbs()

如图加上第8行的return就可以解决了。下面我们在看看改后的程序输出:

————————

welcome to the index page
Username:jack
Password:abc123
Authenticate Success!
welcome to the home page
Username:jack
Password:abc123
Authenticate Success!
welcome to the bbs page
I am the return contents   #bbs()的返回值得到了正确的返回

——-——————

好了,返回值的问题解决了.

既然装饰器是一个函数,那装饰器可以有参数吗?

答案是肯定的。我们同样可以给装饰器加上参数。比如还是上面的三个页面函数作为例子,我们可以根据不同页面的验证方式来给程序不同的验证,而这个验证方式可以以装饰器的参数传入,这样我们就得在装饰器上在嵌套一层函数 了:

 1 username,passwd="jack","abc123"#模拟一个已登录用户
 2 def decorator(auth_type):
 3     def out_warpper(func):
 4         def warpper(*args,**kwargs):
 5             Username=input("Username:").strip()
 6             password=input("Password:").strip()
 7             if auth_type=="local":
 8                 if username==Username and passwd==password:
 9                     print("Authenticate Success!")
10                     return func(*args,**kwargs)
11                 else:
12                     exit("Username or password is invalid!")
13             elif auth_type=="unlocal":
14                 print("HERE IS UNLOCAL AUTHENTICATE WAYS")
15         return warpper
16     return out_warpper
17 
18 def index():
19     print("welcome to the index page")
20 @decorator(auth_type="local")
21 def home():
22     print("welcome to the home page")
23 @decorator(auth_type="unlocal")
24 def bbs():
25     print("welcome to the bbs page")
26     return "I am the return contents"
27 
28 index()
29 home()
30 bbs()

输出:

————————

welcome to the index page
Username:jack
Password:abc123
Authenticate Success!
welcome to the home page
Username:jack
Password:abc123
HERE IS UNLOCAL AUTHENTICATE WAYS

————————

可见,程序分别加入了第2行和第16行和中间的根据auth_type参数的判断的相关内容后, 就解决上述问题了。对于上面的这一个三层嵌套的相关逻辑,大家可以在 pycharm里头加上断点,逐步调试,便可发现其中的道理。

总结

要想学好迭代器就必须理解一下三条:

1.函数即变量(即函数对象的概念)

2.函数嵌套

3.函数式编程

 

猜你喜欢

转载自blog.csdn.net/qq_38584967/article/details/78873483