Am 15.01.2013 15:20 schrieb contro opinion:
>>> def deco(func):
... def kdeco():
... print("before myfunc() called.")
... func()
... print(" after myfunc() called.")
... return kdeco
...
>>> @deco
... def myfunc():
... print(" myfunc() called.")
...
>>> myfunc()
before myfunc() called.
myfunc() called.
after myfunc() called.
>>> deco(myfunc)()
before myfunc() called.
before myfunc() called.
myfunc() called.
after myfunc() called.
after myfunc() called.
Wrapping works this way:
The function is defined, and the wrapper replaces the function with a
different one which (in this case) calls the original one.
Try print(myfunc) here and you see that myfunc is only a name for
another function called kdeco. It is the one returned by the decorator.
1.
why there are two lines :before myfunc() called.and tow lines :after
myfunc() called. in the output?
This is because the "before" line is printed, then the modified "myfunc"
is called, which in turn prints another "before" line and then calls the
"really original" function. After it returns, the "after" line is called
by the inner placement function (the one which sticks at the myfunc
identifier). This function returns and the function instance which
called the first "before" line is printed then.
2.why the result is not
before myfunc() called.
myfunc() called.
after myfunc() called.
before myfunc() called.
myfunc() called.
after myfunc() called.
Because the function calls are wrapped and not repeated.
Thomas
--
http://mail.python.org/mailman/listinfo/python-list