Re: i can't understand decorator

Discussion in 'Python' started by Oscar Benjamin, Jan 15, 2013.

  1. On 15 January 2013 14:20, contro opinion <> 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
     
    Oscar Benjamin, Jan 15, 2013
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Sakesun Roykiattisak
    Replies:
    1
    Views:
    256
    Christopher T King
    Aug 5, 2004
  2. glomde
    Replies:
    5
    Views:
    547
    glomde
    Mar 29, 2007
  3. Saqib Ali
    Replies:
    4
    Views:
    214
    Ethan Furman
    Dec 22, 2011
  4. contro opinion

    i can't understand decorator

    contro opinion, Jan 15, 2013, in forum: Python
    Replies:
    1
    Views:
    149
    Thomas Rachel
    Jan 15, 2013
  5. Mark Carter
    Replies:
    2
    Views:
    175
    Steven D'Aprano
    Jan 18, 2013
Loading...

Share This Page