#!/usr/bin/python**加粗文字**
def deco_functionNeedDoc(func):
if func.__doc__ == None:
print func,"has no __doc__, it's a bad habit."
else:
print func,':',func.__doc__,'.'
return func
@deco_functionNeedDoc
def f():
print 'f() Do something'
@deco_functionNeedDoc
def g():
'I have a __doc__'
print 'g() Do something'
f()
g()
Actual Result:
<function f at 0x7f31e65d05f0> has no __doc__, it's a bad habit.
<function g at 0x7f31e65d0668> : I have a doc .
f() Do something
g() Do something
Expected Result:
<function f at 0x7f31e65d05f0> has no __doc__, it's a bad habit.
f() Do something
<function g at 0x7f31e65d0668> : I have a doc .
g() Do something
f()和g()被修饰后是如何执行的?
另外一段使用装饰器的代码
#-*- coding: UTF-8 -*-
import time
def timeit(func):
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
return wrapper
@timeit
def foo():
print 'in foo()'
foo()
Actual Result:
in foo()
used: 2.1e-05
这一段使用wrapper方法执行时先执行foo(),再执行wrapper()。
加了wrapper会有什么差别吗?
The decorator is more like a program executed "at compile time". It "decorates" the function even before the original function is loaded into the memory, so here is the decorated function that is decorated first and then run. Otherwise, you can try to execute the code in the decorated function without executing f() or g() at the end
The function is re-bound after passing the decorator, which means
So the decorator should be part of the function object. In other words, this step is that the code is "hard-coded" during compilation, that is, when it is compiled into bytecode. This is similar to the default function of the function. Parameter
They are all determined during the compilation stage. So, your code is definitely explained. In the compilation phase, the decorator is first executed to rebind the function, and then in the execution phase, the things in f are directly run.
PS: Your example of decorator is not typical. You can find some that wrap the original function
The above is my personal understanding, let’s discuss together
The modified
wrap
decorator function is actually thetimeit
function that is executed first, but it does not output anything, but directly returns a function object. . For example, if you add:wrap
装饰器函数, 其实也是先执行的timeit
这个函数,只不过没有输出东西,而是直接返回了一个函数对象而已。比如你这样加一句:输出就会变了,先输出
The output will change, first outputI am timeit
. 你再看看我上面说的,装饰器就是把函数重新绑定,返回另一个函数。 是在编译时期完成的, 再执行的时候,直接执行新函数。也就是你的wrapper
rrreeeI am timeit
. Look at what I said above, the decorator rebinds the function and returns another function. It is completed during compilation, and when executed again, the new function will be executed directly. That is yourwrapper
#🎜🎜#