Re: confused in decorate and closure

Discussion in 'Python' started by Peter Otten, Sep 13, 2012.

  1. Peter Otten

    Peter Otten Guest

    月忧茗 wrote:

    > HI, I have some test code:
    >
    >
    > def num(num):
    > def deco(func):
    > def wrap(*args, **kwargs):
    > inputed_num = num
    > return func(*args, **kwargs)
    > return wrap
    > return deco
    >
    >
    > @num(5)
    > def test(a):
    > return a + inputed_num
    >
    > print test(1)
    >
    >
    > when run this code, I got an error shows that 'inputed_num' is not
    > defined
    >
    > My question is:
    > In wrap function, is there not a closure that func can got 'inputed_num'
    > ?
    >
    >
    >
    > Anyway, If not, how should I do to got my aim: Initialize some value,
    > and use this value directly in the main function.


    Variable scopes are determined statically. In

    > def test(a):
    > return a + inputed_num


    "inputed_num" is a global variable.

    > @num(5)


    is not a macro, but a shortcut that tells Python to execute

    test = num(5)(test)

    and thus does not change the scopes. To get the desired effect you have to
    turn "inputed_num" into an explicit function argument, for example:

    >>> def num(n):

    .... def deco(f):
    .... def wrap(*args, **kw):
    .... return f(n, *args, **kw)
    .... return wrap
    .... return deco
    ....
    >>> @num(42)

    .... def test(n, a):
    .... return n + a
    ....
    >>> test(1)

    43
     
    Peter Otten, Sep 13, 2012
    #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. Umut Tezduyar
    Replies:
    0
    Views:
    435
    Umut Tezduyar
    Nov 22, 2005
  2. Roger Varley

    Extend or Decorate?

    Roger Varley, Jan 18, 2006, in forum: Java
    Replies:
    3
    Views:
    709
    Michael Redlich
    Jan 18, 2006
  3. Thomas Philips
    Replies:
    2
    Views:
    346
    Paul McGuire
    Jun 23, 2004
  4. Javier_CH

    RGL: decorate nodes and edges

    Javier_CH, Mar 29, 2007, in forum: Ruby
    Replies:
    4
    Views:
    192
    Javier Vázquez
    Mar 30, 2007
  5. Julian Mehnle
    Replies:
    0
    Views:
    262
    Julian Mehnle
    Jul 17, 2003
Loading...

Share This Page