Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #29016 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2012-09-13 08:32 +0200 |
| Last post | 2012-09-13 08:32 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: confused in decorate and closure Peter Otten <__peter__@web.de> - 2012-09-13 08:32 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2012-09-13 08:32 +0200 |
| Subject | Re: confused in decorate and closure |
| Message-ID | <mailman.594.1347517951.27098.python-list@python.org> |
月忧茗 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
Back to top | Article view | comp.lang.python
csiph-web