i can't understand decorator

C

contro opinion

def deco(func):
.... def kdeco():
.... print("before myfunc() called.")
.... func()
.... print(" after myfunc() called.")
.... return kdeco
........ def myfunc():
.... print(" myfunc() called.")
....before myfunc() called.
myfunc() called.
after myfunc() called.before myfunc() called.
before myfunc() called.
myfunc() called.
after myfunc() called.
after myfunc() called.
1.
why there are two lines :before myfunc() called.and tow lines :after
myfunc() called. in the output?
2.why the result is not
before myfunc() called.
myfunc() called.
after myfunc() called.
before myfunc() called.
myfunc() called.
after myfunc() called.
 
T

Thomas Rachel

Am 15.01.2013 15:20 schrieb contro opinion:
... def kdeco():
... print("before myfunc() called.")
... func()
... print(" after myfunc() called.")
... return kdeco
...
... def myfunc():
... print(" myfunc() called.")
...
before myfunc() called.
myfunc() called.
after myfunc() called.
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top