Home > other >  Python closure
Python closure

Time:11-28

Learning and fluent in python closures have code
The import time

Def clock (func) :
Def clocked (* args) :
T0=time. Perf_counter ()
Result=func (* args)
Elapsed time of=. Perf_counter () - t0

Name=func. __name__

Arg_str=', '. Join (repr (arg) for arg in the args)

Print (' 0.8 fs] [% % s (% s) - & gt; % r '% (elapsed, name, arg_str, result))

Return the result

Return clocked

@ clock
Def snooze (seconds) :
Time. Sleep (seconds)

@ clock
Def factorial (n) :
Return 1 if n<2 the else n * factorial (n - 1)

If __name__=="__main__ ':
Print (' * '* 50,' calling snooze (. 123) ')
Snooze (. 123)
Print (' * '* 50)
Snooze (. 567)

Print (' * '* 50,' calling factor (6) ')
Print (' 6!=', factorial (6))
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Above is the book of the source output, and the book is consistent and understanding is consistent

According to understand first calls the decorator again calls func code below but no press understanding the order of the output


Registry=set ()
Def register (active=True) :
N=0
Def decorate (func) :
Nonlocal n
Print (' running the register (active)=% s - & gt; Decorate (% s) '% (active, func))
# print (' must be output ')
If the active:
Registry. The add (func)
The else:
Registry. Discard (func)
# func ()
Print (' must be output % s' % repr (n))
Return func
# print (' must be output ')
N=n + 1
Return decorate

@ register (active=False)
Def f1 () :
Print (' running in f1 ')

@ the register ()
Def f2 () :
Print (' running in f2 ')

If __name__=="__main__ ':
F1 ()
F2 ()
F2 ()
F1 ()
Print (registry)


-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- should understand each call to the output must be output the
Running the register (active=False) - & gt; Decorate (& lt; The function f1 at 0 x7f6e1fb082f0 & gt;)
Must be the output 1
Running the register (active=True) - & gt; Decorate (& lt; The function f2 at 0 x7f6e1fb08620 & gt;)
Must be the output 1
Running in f1
Running in f2
Running in f2
Running in f1
{& lt; The function f2 at 0 x7f6e1fb08620 & gt; }

Hard to help answer not according to the number of output must be the output of the reasons many thanks!
  • Related