转载www.shenrenshequ.com
为了理解装饰器,你首先必须知道 Python 中的函数都是 object 对象。 这非常重要。让我们通过一个例子来看看原因。
Python
def shout(word='yes'):
return word.capitalize() + '!'
print shout()
outputs : 'Yes!'
作为一个 object 对象,你可以把一个函数分配给一个变量,就像是
其他 object 对象一样
scream = shout
请注意我们并没有使用括号:因此我们没有调用函数,我们只是把函数 shout
赋值给变量 scream
这意味着我们可以通过 scream
调用 shout
函数
print scream()
outputs : 'Yes!'
除了这些,这还意味着你可以移除旧的函数名 shout
,
之后依然可以通过 scream
访问函数
del shout
try:
print shout()
except NameError as e:
print e
#outputs: "name 'shout' is not defined"
print scream()
outputs: 'Yes!'
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
def shout(word='yes'):
return word.capitalize() + '!'
print shout()
outputs : 'Yes!'
作为一个 object 对象,你可以把一个函数分配给一个变量,就像是
其他 object 对象一样
scream = shout
请注意我们并没有使用括号:因此我们没有调用函数,我们只是把函数 shout
赋值给变量 scream
这意味着我们可以通过 scream
调用 shout
函数
print scream()
outputs : 'Yes!'
除了这些,这还意味着你可以移除旧的函数名 shout
,
之后依然可以通过 scream
访问函数
del shout
try:
print shout()
except NameError as e:
print e
#outputs: "name 'shout' is not defined"
print scream()
outputs: 'Yes!'
记住上面的内容,一会我们还会用得到。
Python 函数另一个有趣的性质在于它们可以。。。在另一个函数内部定义!
Python
def talk():
# 你可以在 `talk` 函数临时定义一个函数
def whisper(word='yes'):
return word.lower() + '...'
# ... 之后直接使用这个函数
print whisper()
你可以调用 talk
函数,每次调用这个函数都会定义 whisper
函数,并且
在 talk
函数中调用 whisper
函数
talk()
outputs:
"yes..."
但是 whisper
函数在 talk
函数外部并不存在:
try:
print whisper()
except NameError as e:
print e
#outputs : "name 'whisper' is not defined"*
#Python's functions are objects
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
def talk():
# 你可以在 `talk` 函数临时定义一个函数
def whisper(word='yes'):
return word.lower() + '...'
# ... 之后直接使用这个函数
print whisper()
你可以调用 talk
函数,每次调用这个函数都会定义 whisper
函数,并且
在 talk
函数中调用 whisper
函数
talk()
outputs:
"yes..."
但是 whisper
函数在 talk
函数外部并不存在:
try:
print whisper()
except NameError as e:
print e
#outputs : "name 'whisper' is not defined"*
#Python's functions are objects
函数引用
现在是比较有趣的部分。。。
你已经知道了函数是 object 对象。此外,函数还:
可以像变量一样赋值
可以在另一个函数内部定义
这表示 函数可以 return 另一个函数。看下面吧!
Python
def getTalk(kind='shout'):
# 我们临时定义一个函数
def shout(word='yes'):
return word.capitalize() + '!'
def whisper(word='yes'):
return word.lower() + '...'
# 然后我们返回上面两个函数中的一个
if kind == 'shout':
# 我们并没有使用 '()' 。因此我们并没有调用函数;
# 相反,我们返回了函数对象
return shout
else:
return whisper
你该怎样使用这个奇怪的功能呢?
调用这个函数,然后把结果赋值给一个变量
talk = getTalk()
你可以看到 talk
是一个函数对象:
print talk
outputs :
The object is the one returned by the function:
这个对象是由一个函数返回的
print talk()
outputs : Yes!
如果你觉得奇怪的话,你甚至可以直接使用它
print getTalk('whisper')()
outputs : yes...
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
37
def getTalk(kind='shout'):
# 我们临时定义一个函数
def shout(word='yes'):
return word.capitalize() + '!'
def whisper(word='yes'):
return word.lower() + '...'
# 然后我们返回上面两个函数中的一个
if kind == 'shout':
# 我们并没有使用 '()' 。因此我们并没有调用函数;
# 相反,我们返回了函数对象
return shout
else:
return whisper
你该怎样使用这个奇怪的功能呢?
调用这个函数,然后把结果赋值给一个变量
talk = getTalk()
你可以看到 talk
是一个函数对象:
print talk
outputs :
The object is the one returned by the function:
这个对象是由一个函数返回的
print talk()
outputs : Yes!
如果你觉得奇怪的话,你甚至可以直接使用它
print getTalk('whisper')()
outputs : yes...
但等等…还有一些内容!
如果你可以 return 一个函数,那么你也可以把函数当作参数传递:
Python
def doSomethingBefore(func):
print 'I do something before then I call the function you gave me'
print func()
doSomethingBefore(scream)
outputs:
I do something before then I call the function you gave me
Yes!
1
2
3
4
5
6
7
8
def doSomethingBefore(func):
print 'I do something before then I call the function you gave me'
print func()
doSomethingBefore(scream)
outputs:
I do something before then I call the function you gave me
Yes!
好,你已经掌握了装饰器所需的全部知识。正如你所见,装饰器是“包装器”,也就是说 它们允许你在它们装饰的函数的前面和后面运行其他代码 ,而不必修改函数本身。
动手制作装饰器
你应该怎样动手制作:
Python
装饰器是把其他函数作为参数的函数
def my_shiny_new_decorator(a_function_to_decorate):
# 在装饰器内部,装饰器临时创建了一个函数: 包装器。
# 这个函数把原来的函数包装起来
# 因此它可以在原函数的前面和后面执行其他代码。
def the_wrapper_around_the_original_function():
# 把你想在原函数被调用前执行的代码写在这里
print 'Before the function runs'
# 在这里调用原函数(使用括号)
a_function_to_decorate()
# 把你想在原函数调用后执行的代码写在这里
print 'After the function runs'
# 到目前为止,`a_function_to_decorate` 还从未执行过。
# 我们返回刚刚创建的包装器
# 包装器中包含了原函数和在原函数之前/之后执行的代码。现在已经可以使用了!
return the_wrapper_around_the_original_function
现在想象一下你创建了一个函数,你不想再改动它了。
def a_stand_alone_function():
print 'I am a stand alone function, don’t you dare modify me'
a_stand_alone_function()
outputs: I am a stand alone function, don't you dare modify me
好的,你可以装饰这个函数来扩展它的功能
只需要把它传递给装饰器,之后就会动态地包装在你需要的任何代码中,然后返回一个满足你需求的新函数:
a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function_decorated()
outputs:
Before the function runs
I am a stand alone function, don't you dare modify me
After the function runs
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
37
装饰器是把其他函数作为参数的函数
def my_shiny_new_decorator(a_function_to_decorate):
# 在装饰器内部,装饰器临时创建了一个函数: 包装器。
# 这个函数把原来的函数包装起来
# 因此它可以在原函数的前面和后面执行其他代码。
def the_wrapper_around_the_original_function():
# 把你想在原函数被调用前执行的代码写在这里
print 'Before the function runs'
# 在这里调用原函数(使用括号)
a_function_to_decorate()
# 把你想在原函数调用后执行的代码写在这里
print 'After the function runs'
# 到目前为止,`a_function_to_decorate` 还从未执行过。
# 我们返回刚刚创建的包装器
# 包装器中包含了原函数和在原函数之前/之后执行的代码。现在已经可以使用了!
return the_wrapper_around_the_original_function
现在想象一下你创建了一个函数,你不想再改动它了。
def a_stand_alone_function():
print 'I am a stand alone function, don’t you dare modify me'
a_stand_alone_function()
outputs: I am a stand alone function, don't you dare modify me
好的,你可以装饰这个函数来扩展它的功能
只需要把它传递给装饰器,之后就会动态地包装在你需要的任何代码中,然后返回一个满足你需求的新函数:
a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function_decorated()
outputs:
Before the function runs
I am a stand alone function, don't you dare modify me
After the function runs
现在,你希望每次你调用 a_stand_alone_function 的时候,实际上 a_stand_alone_function_decorated 会被调用。也就是说,这只是用 my_shiny_new_decorator 返回的函数重写了 a_stand_alone_function 函数:
Python
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
outputs:
Before the function runs
I am a stand alone function, don’t you dare modify me
After the function runs
你猜怎样着?这实际上就是装饰器的原理!
1
2
3
4
5
6
7
8
a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
outputs:
Before the function runs
I am a stand alone function, don’t you dare modify me
After the function runs
你猜怎样着?这实际上就是装饰器的原理!
装饰器解密
和前面相同的例子,但是使用了装饰器语法:
Python
@my_shiny_new_decorator
def another_stand_alone_function():
print 'Leave me alone'
another_stand_alone_function()
outputs:
Before the function runs
Leave me alone
After the function runs
1
2
3
4
5
6
7
8
9
@my_shiny_new_decorator
def another_stand_alone_function():
print 'Leave me alone'
another_stand_alone_function()
outputs:
Before the function runs
Leave me alone
After the function runs
就是这样,装饰器就是这么简单。 @decorator 只是下面形式的简写:
Python
another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)
1
another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)
装饰器只是一个 pythonic 的装饰器设计模式的变种。Python 中内置了许多种传统的设计模式来简化开发过程(例如迭代器)。
当然,你可以叠加多个装饰器:
Python
def bread(func):
def wrapper():
print "</''''''\>"
func()
print "<\______/>"
return wrapper
def ingredients(func):
def wrapper():
print '#tomatoes#'
func()
print '~salad~'
return wrapper
def sandwich(food='--ham--'):
print food
sandwich()
outputs: --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
outputs:
''''''>
tomatoes
--ham--
~salad~
<______/>
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
def bread(func):
def wrapper():
print "</''''''\>"
func()
print "<\______/>"
return wrapper
def ingredients(func):
def wrapper():
print '#tomatoes#'
func()
print '~salad~'
return wrapper
def sandwich(food='--ham--'):
print food
sandwich()
outputs: --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
outputs:
''''''>
tomatoes
--ham--
~salad~
<______/>
使用 Python 的装饰器语法:
Python
@bread
@ingredients
def sandwich(food='--ham--'):
print food
sandwich()
outputs:
''''''>
tomatoes
--ham--
~salad~
<______/>
1
2
3
4
5
6
7
8
9
10
11
12
@bread
@ingredients
def sandwich(food='--ham--'):
print food
sandwich()
outputs:
''''''>
tomatoes
--ham--
~salad~
<______/>
你设置装饰器的顺序很重要:
Python
@ingredients
@bread
def strange_sandwich(food='--ham--'):
print food
strange_sandwich()
outputs:
tomatoes
''''''>
--ham--
<______/>
~salad~
1
2
3
4
5
6
7
8
9
10
11
12
@ingredients
@bread
def strange_sandwich(food='--ham--'):
print food
strange_sandwich()
outputs:
tomatoes
''''''>
--ham--
<______/>
~salad~
现在:是时候回答问题了。。。
现在你很容易就知道怎样回答这个问题了:
Python
生成粗体(bold)的装饰器
def makebold(fn):
# 装饰器返回的新函数
def wrapper():
# 在之前和之后插入其他代码
return '<b>' + fn() + '</b>'
return wrapper
生成斜体的装饰器
def makeitalic(fn):
# 装饰器返回的新函数
def wrapper():
# 在函数执行前后插入一些代码
return '<i>' + fn() + '</i>'
return wrapper
@makebold
@makeitalic
def say():
return 'hello'
print say()
outputs: hello
和上面完全等价的形式
def say():
return 'hello'
say = makebold(makeitalic(say))
print say()
outputs: hello
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
生成粗体(bold)的装饰器
def makebold(fn):
# 装饰器返回的新函数
def wrapper():
# 在之前和之后插入其他代码
return '<b>' + fn() + '</b>'
return wrapper
生成斜体的装饰器
def makeitalic(fn):
# 装饰器返回的新函数
def wrapper():
# 在函数执行前后插入一些代码
return '<i>' + fn() + '</i>'
return wrapper
@makebold
@makeitalic
def say():
return 'hello'
print say()
outputs: hello
和上面完全等价的形式
def say():
return 'hello'
say = makebold(makeitalic(say))
print say()
outputs: hello
现在你该放下轻松的心态,好好看看装饰器的高级使用方法了。
把装饰器传到下一层去
把参数传递给被装饰的函数
Python
这并不是黑魔法,你只是让包装器传递参数而已
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(arg1, arg2):
print 'I got args! Look:', arg1, arg2
function_to_decorate(arg1, arg2)
return a_wrapper_accepting_arguments
因为当你调用装饰器返回的函数时,实际上你在调用包装器,把参数传递给包装器,这也就完成了把参数传递给装饰器函数
@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
print 'My name is', first_name, last_name
print_full_name('Peter', 'Venkman')
outputs:
I got args! Look: Peter Venkman
My name is Peter Venkman
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
这并不是黑魔法,你只是让包装器传递参数而已
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(arg1, arg2):
print 'I got args! Look:', arg1, arg2
function_to_decorate(arg1, arg2)
return a_wrapper_accepting_arguments
因为当你调用装饰器返回的函数时,实际上你在调用包装器,把参数传递给包装器,这也就完成了把参数传递给装饰器函数
@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
print 'My name is', first_name, last_name
print_full_name('Peter', 'Venkman')
outputs:
I got args! Look: Peter Venkman
My name is Peter Venkman
装饰器方法
关于 Python 的一个优点就是方法和函数本质本质上是一样的。二者唯一的区别就是方法的第一个参数是对当前对象的引用 (self)。
这意味着你可以按照同样的方式为方法创建装饰器!只要记得考虑 self 就可以了:
Python
def method_friendly_decorator(method_to_decorate):
def wrapper(self, lie):
lie = lie - 3 # very friendly, decrease age even more :-)
return method_to_decorate(self, lie)
return wrapper
class Lucy(object):
def __init__(self):
self.age = 32
@method_friendly_decorator
def sayYourAge(self, lie):
print 'I am {0}, what did you think?'.format(self.age + lie)
l = Lucy()
l.sayYourAge(-3)
outputs: I am 26, what did you think?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def method_friendly_decorator(method_to_decorate):
def wrapper(self, lie):
lie = lie - 3 # very friendly, decrease age even more :-)
return method_to_decorate(self, lie)
return wrapper
class Lucy(object):
def __init__(self):
self.age = 32
@method_friendly_decorator
def sayYourAge(self, lie):
print 'I am {0}, what did you think?'.format(self.age + lie)
l = Lucy()
l.sayYourAge(-3)
outputs: I am 26, what did you think?
如果你在创建通用的装饰器 — 一个适用于任何函数或者方法的装饰器,无论参数是什么 — 那么只要使用 args, *kwargs就可以了:
Python
def a_decorator_passing_arbitrary_arguments(function_to_decorate):
# 包装器接受任何参数
def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
print 'Do I have args?:'
print args
print kwargs
# 接下来解包参数,也就是这里的 *args, **kwargs
# 如果你不熟悉解包,可以浏览这个:
# http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
function_to_decorate(*args, **kwargs)
return a_wrapper_accepting_arbitrary_arguments
@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():
print 'Python is cool, no argument here.'
function_with_no_argument()
outputs
Do I have args?:
()
{}
Python is cool, no argument here.
@a_decorator_passing_arbitrary_arguments
def function_with_arguments(a, b, c):
print a, b, c
function_with_arguments(1,2,3)
outputs
Do I have args?:
(1, 2, 3)
{}
1 2 3
@a_decorator_passing_arbitrary_arguments
def function_with_named_arguments(a, b, c, platypus='Why not ?'):
print 'Do {0}, {1} and {2} like platypus? {3}'.format(
a, b, c, platypus)
function_with_named_arguments('Bill', 'Linus', 'Steve', platypus='Indeed!')
outputs
Do I have args ? :
('Bill', 'Linus', 'Steve')
{'platypus': 'Indeed!'}
Do Bill, Linus and Steve like platypus? Indeed!
class Mary(object):
def __init__(self):
self.age = 31
@a_decorator_passing_arbitrary_arguments
def sayYourAge(self, lie=-3): #你可以在这里添加默认值
print 'I am {0}, what did you think?'.format(self.age + lie)
m = Mary()
m.sayYourAge()
outputs
Do I have args?:
(<__main__.Mary object at 0xb7d303ac>,)
{}
I am 28, what did you think?
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def a_decorator_passing_arbitrary_arguments(function_to_decorate):
# 包装器接受任何参数
def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
print 'Do I have args?:'
print args
print kwargs
# 接下来解包参数,也就是这里的 *args, **kwargs
# 如果你不熟悉解包,可以浏览这个:
# http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
function_to_decorate(*args, **kwargs)
return a_wrapper_accepting_arbitrary_arguments
@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():
print 'Python is cool, no argument here.'
function_with_no_argument()
outputs
Do I have args?:
()
{}
Python is cool, no argument here.
@a_decorator_passing_arbitrary_arguments
def function_with_arguments(a, b, c):
print a, b, c
function_with_arguments(1,2,3)
outputs
Do I have args?:
(1, 2, 3)
{}
1 2 3
@a_decorator_passing_arbitrary_arguments
def function_with_named_arguments(a, b, c, platypus='Why not ?'):
print 'Do {0}, {1} and {2} like platypus? {3}'.format(
a, b, c, platypus)
function_with_named_arguments('Bill', 'Linus', 'Steve', platypus='Indeed!')
outputs
Do I have args ? :
('Bill', 'Linus', 'Steve')
{'platypus': 'Indeed!'}
Do Bill, Linus and Steve like platypus? Indeed!
class Mary(object):
def __init__(self):
self.age = 31
@a_decorator_passing_arbitrary_arguments
def sayYourAge(self, lie=-3): #你可以在这里添加默认值
print 'I am {0}, what did you think?'.format(self.age + lie)
m = Mary()
m.sayYourAge()
outputs
Do I have args?:
(<__main__.Mary object at 0xb7d303ac>,)
{}
I am 28, what did you think?
把参数传递给装饰器
太棒了,现在你对于把参数传递给装饰器本身有什么看法呢?
这可能有点奇怪,因为装饰器必须接收一个函数作为参数。因此,你可能无法直接把装饰器函数作为参数传递给另一个装饰器。
在得到答案之前,让我们写一个小的例子:
Python
装饰器是普通函数
def my_decorator(func):
print 'I am an ordinary function'
def wrapper():
print 'I am function returned by the decorator'
func()
return wrapper
因此你可以在没有任何 '@' 的情况下调用它
def lazy_function():
print 'zzzzzzzz'
decorated_function = my_decorator(lazy_function)
outputs: I am an ordinary function
上面的函数输出 'I am an ordinary function' ,因为这实际上就是我们直接调用函数的结果。没什么好奇怪的。
@my_decorator
def lazy_function():
print 'zzzzzzzz'
outputs: I am an ordinary function
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
装饰器是普通函数
def my_decorator(func):
print 'I am an ordinary function'
def wrapper():
print 'I am function returned by the decorator'
func()
return wrapper
因此你可以在没有任何 '@' 的情况下调用它
def lazy_function():
print 'zzzzzzzz'
decorated_function = my_decorator(lazy_function)
outputs: I am an ordinary function
上面的函数输出 'I am an ordinary function' ,因为这实际上就是我们直接调用函数的结果。没什么好奇怪的。
@my_decorator
def lazy_function():
print 'zzzzzzzz'
outputs: I am an ordinary function
结果是一模一样的:my_decorator 被调用了。因此当你使用 @my_decorator 时,Python 会调用 “my_decorator” 变量所代表的函数。
这很重要!你提供的这个变量可以指向装饰器,也可以不指向。
让我们增加点难度。
Python
def decorator_maker():
print 'I make decorators! I am executed only once: '+\
'when you make me create a decorator.'
def my_decorator(func):
print 'I am a decorator! I am executed only when you decorate a function.'
def wrapped():
print ('I am the wrapper around the decorated function. '
'I am called when you call the decorated function. '
'As the wrapper, I return the RESULT of the decorated function.')
return func()
print 'As the decorator, I return the wrapped function.'
return wrapped
print 'As a decorator maker, I return a decorator'
return my_decorator
让我们创建一个装饰器。本质上是一个新函数
new_decorator = decorator_maker()
outputs:
I make decorators! I am executed only once: when you make me create a decorator.
As a decorator maker, I return a decorator
然后我们装饰下面这个函数
def decorated_function():
print 'I am the decorated function.'
decorated_function = new_decorator(decorated_function)
outputs:
I am a decorator! I am executed only when you decorate a function.
As the decorator, I return the wrapped function
调用这个函数
decorated_function()
outputs:
I am the wrapper around the decorated function. I am called when you call the decorated function.
As the wrapper, I return the RESULT of the decorated function.
I am the decorated function.
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
37
38
39
40
41
42
43
44
45
46
def decorator_maker():
print 'I make decorators! I am executed only once: '+\
'when you make me create a decorator.'
def my_decorator(func):
print 'I am a decorator! I am executed only when you decorate a function.'
def wrapped():
print ('I am the wrapper around the decorated function. '
'I am called when you call the decorated function. '
'As the wrapper, I return the RESULT of the decorated function.')
return func()
print 'As the decorator, I return the wrapped function.'
return wrapped
print 'As a decorator maker, I return a decorator'
return my_decorator
让我们创建一个装饰器。本质上是一个新函数
new_decorator = decorator_maker()
outputs:
I make decorators! I am executed only once: when you make me create a decorator.
As a decorator maker, I return a decorator
然后我们装饰下面这个函数
def decorated_function():
print 'I am the decorated function.'
decorated_function = new_decorator(decorated_function)
outputs:
I am a decorator! I am executed only when you decorate a function.
As the decorator, I return the wrapped function
调用这个函数
decorated_function()
outputs:
I am the wrapper around the decorated function. I am called when you call the decorated function.
As the wrapper, I return the RESULT of the decorated function.
I am the decorated function.
没什么意料之外的事情发生。
我们再做一次上面的事情,只不过这一次取消掉所有的中间变量:
Python
def decorated_function():
print 'I am the decorated function.'
decorated_function = decorator_maker()(decorated_function)
outputs:
I make decorators! I am executed only once: when you make me create a decorator.
As a decorator maker, I return a decorator
I am a decorator! I am executed only when you decorate a function.
As the decorator, I return the wrapped function.
最后:
decorated_function()
outputs:
I am the wrapper around the decorated function. I am called when you call the decorated function.
As the wrapper, I return the RESULT of the decorated function.
I am the decorated function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def decorated_function():
print 'I am the decorated function.'
decorated_function = decorator_maker()(decorated_function)
outputs:
I make decorators! I am executed only once: when you make me create a decorator.
As a decorator maker, I return a decorator
I am a decorator! I am executed only when you decorate a function.
As the decorator, I return the wrapped function.
最后:
decorated_function()
outputs:
I am the wrapper around the decorated function. I am called when you call the decorated function.
As the wrapper, I return the RESULT of the decorated function.
I am the decorated function.
让它更短一下:
Python
@decorator_maker()
def decorated_function():
print 'I am the decorated function.'
outputs:
I make decorators! I am executed only once: when you make me create a decorator.
As a decorator maker, I return a decorator
I am a decorator! I am executed only when you decorate a function.
As the decorator, I return the wrapped function.
最后:
decorated_function()
outputs:
I am the wrapper around the decorated function. I am called when you call the decorated function.
As the wrapper, I return the RESULT of the decorated function.
I am the decorated function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@decorator_maker()
def decorated_function():
print 'I am the decorated function.'
outputs:
I make decorators! I am executed only once: when you make me create a decorator.
As a decorator maker, I return a decorator
I am a decorator! I am executed only when you decorate a function.
As the decorator, I return the wrapped function.
最后:
decorated_function()
outputs:
I am the wrapper around the decorated function. I am called when you call the decorated function.
As the wrapper, I return the RESULT of the decorated function.
I am the decorated function.
你注意到了吗?我们调用了一个 @ 语法的函数! :-)
所以,回到装饰器的参数上面来。如果我们可以使用函数生成一个临时的装饰器,我们也可以把参数传递给那个函数,对吗?
Python
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):
print 'I make decorators! And I accept arguments:', decorator_arg1, decorator_arg2
def my_decorator(func):
# 传递参数的能力来自于闭包
# 如果你不了解闭包,那也没关系,
# 或者你也可以阅读 http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
print 'I am the decorator. Somehow you passed me arguments:', decorator_arg1, decorator_arg2
# 不要混淆装饰器参数和函数参数!
def wrapped(function_arg1, function_arg2):
print ('I am the wrapper around the decorated function.\n'
'I can access all the variables\n'
'\t- from the decorator: {0} {1}\n'
'\t- from the function call: {2} {3}\n'
'Then I can pass them to the decorated function'
.format(decorator_arg1, decorator_arg2,
function_arg1, function_arg2))
return func(function_arg1, function_arg2)
return wrapped
return my_decorator
@decorator_maker_with_arguments('Leonard', 'Sheldon')
def decorated_function_with_arguments(function_arg1, function_arg2):
print ('I am the decorated function and only knows about my arguments: {0}'
' {1}'.format(function_arg1, function_arg2))
decorated_function_with_arguments('Rajesh', 'Howard')
outputs:
I make decorators! And I accept arguments: Leonard Sheldon
I am the decorator. Somehow you passed me arguments: Leonard Sheldon
I am the wrapper around the decorated function.
I can access all the variables
- from the decorator: Leonard Sheldon
- from the function call: Rajesh Howard
Then I can pass them to the decorated function
I am the decorated function and only knows about my arguments: Rajesh Howard
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
37
38
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):
print 'I make decorators! And I accept arguments:', decorator_arg1, decorator_arg2
def my_decorator(func):
# 传递参数的能力来自于闭包
# 如果你不了解闭包,那也没关系,
# 或者你也可以阅读 http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
print 'I am the decorator. Somehow you passed me arguments:', decorator_arg1, decorator_arg2
# 不要混淆装饰器参数和函数参数!
def wrapped(function_arg1, function_arg2):
print ('I am the wrapper around the decorated function.\n'
'I can access all the variables\n'
'\t- from the decorator: {0} {1}\n'
'\t- from the function call: {2} {3}\n'
'Then I can pass them to the decorated function'
.format(decorator_arg1, decorator_arg2,
function_arg1, function_arg2))
return func(function_arg1, function_arg2)
return wrapped
return my_decorator
@decorator_maker_with_arguments('Leonard', 'Sheldon')
def decorated_function_with_arguments(function_arg1, function_arg2):
print ('I am the decorated function and only knows about my arguments: {0}'
' {1}'.format(function_arg1, function_arg2))
decorated_function_with_arguments('Rajesh', 'Howard')
outputs:
I make decorators! And I accept arguments: Leonard Sheldon
I am the decorator. Somehow you passed me arguments: Leonard Sheldon
I am the wrapper around the decorated function.
I can access all the variables
- from the decorator: Leonard Sheldon
- from the function call: Rajesh Howard
Then I can pass them to the decorated function
I am the decorated function and only knows about my arguments: Rajesh Howard
最后得到的就是:带参数的装饰器。参数可以设置为变量:
Python
c1 = 'Penny'
c2 = 'Leslie'
@decorator_maker_with_arguments('Leonard', c1)
def decorated_function_with_arguments(function_arg1, function_arg2):
print ('I am the decorated function and only knows about my arguments:'
' {0} {1}'.format(function_arg1, function_arg2))
decorated_function_with_arguments(c2, 'Howard')
outputs:
I make decorators! And I accept arguments: Leonard Penny
I am the decorator. Somehow you passed me arguments: Leonard Penny
I am the wrapper around the decorated function.
I can access all the variables
- from the decorator: Leonard Penny
- from the function call: Leslie Howard
Then I can pass them to the decorated function
I am the decorated function and only knows about my arguments: Leslie Howard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
c1 = 'Penny'
c2 = 'Leslie'
@decorator_maker_with_arguments('Leonard', c1)
def decorated_function_with_arguments(function_arg1, function_arg2):
print ('I am the decorated function and only knows about my arguments:'
' {0} {1}'.format(function_arg1, function_arg2))
decorated_function_with_arguments(c2, 'Howard')
outputs:
I make decorators! And I accept arguments: Leonard Penny
I am the decorator. Somehow you passed me arguments: Leonard Penny
I am the wrapper around the decorated function.
I can access all the variables
- from the decorator: Leonard Penny
- from the function call: Leslie Howard
Then I can pass them to the decorated function
I am the decorated function and only knows about my arguments: Leslie Howard
如你所见,你可以使用这个技巧向装饰器传递参数,就像是向普通函数传递一样。如果你愿意的话,你甚至可以使用 args, *kwargs。但记住,装饰器只会被调用一次。只在 Python 导入脚本的时候运行。在这之后你就无法动态设置参数了。当你执行 import x 之后,函数已经被装饰了,因此之后你无法改变任何东西。
练习: 装饰一个装饰器
好的,作为奖励,我会提供你一段代码允许装饰器接收任何参数。毕竟,为了接收参数,我们会用另一个函数创建装饰器。
我们包装一下装饰器。
我们最近看到的有包装函数的还有什么呢?
对了,就是装饰器!
让我们做点有趣的事,写一个装饰器的装饰器:
Python
def decorator_with_args(decorator_to_enhance):
"""
这个函数是被用作装饰器。
它会装饰其他函数,被装饰的函数也是一个装饰器。
喝杯咖啡吧。
它允许任何装饰器接收任意个参数,
这样你就不会为每次都要考虑怎样处理而头疼了
"""
# 我们使用同样的技巧来传递参数
def decorator_maker(*args, **kwargs):
# 我们创建一个仅可以接收一个函数的临时装饰器
# 但无法从 maker 传递参数
def decorator_wrapper(func):
# 原装饰器返回的结果
# 其实只是一个普通函数(这个函数返回一个函数)。
# 唯一的陷阱是: 装饰器必须有特定的格式,否则无法运行:
return decorator_to_enhance(func, *args, **kwargs)
return decorator_wrapper
return decorator_maker
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def decorator_with_args(decorator_to_enhance):
"""
这个函数是被用作装饰器。
它会装饰其他函数,被装饰的函数也是一个装饰器。
喝杯咖啡吧。
它允许任何装饰器接收任意个参数,
这样你就不会为每次都要考虑怎样处理而头疼了
"""
# 我们使用同样的技巧来传递参数
def decorator_maker(*args, **kwargs):
# 我们创建一个仅可以接收一个函数的临时装饰器
# 但无法从 maker 传递参数
def decorator_wrapper(func):
# 原装饰器返回的结果
# 其实只是一个普通函数(这个函数返回一个函数)。
# 唯一的陷阱是: 装饰器必须有特定的格式,否则无法运行:
return decorator_to_enhance(func, *args, **kwargs)
return decorator_wrapper
return decorator_maker
可以像下面这样使用:
Python
创建一个用作装饰器的函数。然后加上一个装饰器 :-)
不要忘记,格式是 decorator(func, *args, **kwargs)
@decorator_with_args
def decorated_decorator(func, args, *kwargs):
def wrapper(function_arg1, function_arg2):
print 'Decorated with', args, kwargs
return func(function_arg1, function_arg2)
return wrapper
然后用全新的装饰器装饰你的函数。
@decorated_decorator(42, 404, 1024)
def decorated_function(function_arg1, function_arg2):
print 'Hello', function_arg1, function_arg2
decorated_function('Universe and', 'everything')
outputs:
Decorated with (42, 404, 1024) {}
Hello Universe and everything
Whoooot!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
创建一个用作装饰器的函数。然后加上一个装饰器 :-)
不要忘记,格式是 decorator(func, *args, **kwargs)
@decorator_with_args
def decorated_decorator(func, args, *kwargs):
def wrapper(function_arg1, function_arg2):
print 'Decorated with', args, kwargs
return func(function_arg1, function_arg2)
return wrapper
然后用全新的装饰器装饰你的函数。
@decorated_decorator(42, 404, 1024)
def decorated_function(function_arg1, function_arg2):
print 'Hello', function_arg1, function_arg2
decorated_function('Universe and', 'everything')
outputs:
Decorated with (42, 404, 1024) {}
Hello Universe and everything
Whoooot!
我知道,上次你有这种感觉,是在听一个人说:“在理解递归之前,你必须首先理解递归” 时。但现在,掌握了这个之后你不觉得很棒吗?
最佳实践: 装饰器
装饰器在 Python 2.4 引进,因此确保你的代码运行的 Python 版本 >=2.4
装饰器会拖慢函数调用速度。请牢记
你无法解除装饰一个函数。 (确实 有 一些技巧可以创建允许解除装饰的装饰器,但是没人会使用它们。)因此一旦函数被装饰了,所有这个函数的代码就都装饰了。
装饰器包装函数,会使得函数更难调试。 (从 Python >=2.5 有所好转;看下文。)
functools 模块在 Python 2.5 引进。模块中包含了函数 functools.wraps() ,这个函数会把被装饰函数的名字,模块名,docstring 都复制到它的包装器中。
(有趣的事情是: functools.wraps() 是个装饰器!)
Python
至于调试,stacktrace 输出函数的 name
def foo():
print 'foo'
print foo.__name__
outputs: foo
有了装饰器之后,有点混乱
def bar(func):
def wrapper():
print 'bar'
return func()
return wrapper
@bar
def foo():
print 'foo'
print foo.__name__
outputs: wrapper
functools
可以改善上面的情况
import functools
def bar(func):
# 我们认为 `wrapper` 正在包装 `func`
# 神奇的事情发生了
@functools.wraps(func)
def wrapper():
print 'bar'
return func()
return wrapper
@bar
def foo():
print 'foo'
print foo.__name__
outputs: foo
@counter
@benchmark
@logging
def get_random_futurama_quote():
from urllib import urlopen
result = urlopen('http://subfusion.net/cgi-bin/quote.pl?quote=futurama').read()
try:
value = result.split('<br><b><hr><br>')[1].split('<br><br><hr>')[0]
return value.strip()
except:
return 'No, I’m ... doesn’t!'
print get_random_futurama_quote()
print get_random_futurama_quote()
outputs:
get_random_futurama_quote () {}
wrapper 0.02
wrapper has been used: 1x
The laws of science be a harsh mistress.
get_random_futurama_quote () {}
wrapper 0.01
wrapper has been used: 2x
Curse you, merciful Poseidon!
Python 本身提供了几种装饰器: property ,staticmethod,等
Django 使用装饰器来管理缓存,查看权限。
Twisted 用它来伪造内联异步函数调用。
装饰器的用途确实很广。