i can't understand decorator

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Jan 15 09:31:25 EST 2013


On 15 January 2013 14:20, contro opinion <contropinion at gmail.com> wrote:
>>>> 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.
> 1.
> why there are two lines :before myfunc() called.and tow lines :after
> myfunc() called. in the output?

You have wrapped the function twice with the decorator. Try changing the line
    print("before func() called")
to
    print("about to call", func,__name__)
and you'll see that the function it is about to call is not the same
in both cases.

> 2.why the result is not
> before myfunc() called.
>  myfunc() called.
>   after myfunc() called.
> before myfunc() called.
>  myfunc() called.
>   after myfunc() called.

You would get this output if you just called myfunc() twice. I don't
know why you expect wrapping the function twice to have this effect.


Oscar



More information about the Python-list mailing list