Python decorator
One: function call Order: Similar to other high-level languages, Python does not allow references to or calls to a function before it is declared
Error Demonstration:
def foo (): print ' in the Foo ' bar () Error: In the Foo Traceback (most recent call last): File "<pyshell#13 > ", Line 1, in <module> foo () File" <pyshell#12> ", line 3, foo bar () nameerror:global name ' Bar ' is not defined
def foo (): print ' foo ' bar () foo () def bar (): print ' bar ' ERROR: Nameerror:global name ' bar ' is not defined
Correct demonstration: (Note that Python is executed for interpretation, function Foo has declared bar and Foo before the call, so bar and Foo are not ordered)
def bar (): print ' in the bar ' def foo (): print ' in the Foo ' bar () foo () def foo (): print ' in the foo ' BA R () def bar (): print ' in the Bar ' foo ()
Second: higher-order functions
A function is a higher order function if one of the following conditions is met
Pass a function name as an argument to another function (adding functionality to the adorner function without modifying its source code)
The return value of the function contains n functions, n>0 (does not modify the function's Calling method)
High-order function demonstration:
def bar (): print ' in the bar ' def foo (func): Res=func () return Resfoo (BAR)
The beauty of higher-order functions:
def foo (func): return func print ' function body is%s '% (foo (bar)) print ' Function name is%s '% (foo (bar). Func_name) foo ( Bar) () #foo (bar) () is equivalent to Bar=foo (bar) and then bar () Bar=foo (bar) bar ()
Three: inline functions and variable scopes
Definition: Create another function inside a function called inline function (based on Python support for static nested fields)
Function Nesting Demonstration:
def foo (): Def bar (): print ' In the Bar ' () foo () # Bar ()
Access order of local scope and global scope
X=0def Grandpa (): # X=1 def dad (): x=2 def son (): x=3 print x son () da D () Grandpa ()
Effect of local variable modification on global variables
y=10# def Test (): # y+=1# print y def Test (): # Global y y=2 Print y test () Print Y def dad (): M=1 D EF Son (): n=2 print '---> ', m + N print '--', M Son () dad ()
Four: Closures: If in an intrinsic function, a reference to a variable in the outer scope (but not at the global scope), then the intrinsic function is considered closure
def counter (start_num=0): Count=[start_num] def incr (): Count[0]+=1 return count[0] return incr pri NT counter () print counter () () Print counter () () C=counter () print C () print C ()
Five: inline function + higher order function + closure = "Decorator
Two examples of preheating:
Example one: fixed function parameters
def decorartor (func): Def wrapper (n): print ' starting ' func (n) print ' stopping ' return wrapper def test (n): print ' in the test arg-is%s '%n decorartor (' Alex ')
Example two: The function parameter is not fixed
def decorartor (func): Def wrapper (*args,**kwargs): print ' starting ' func (*args,**kwargs) print ' St Opping ' return wrapper def Test (n,x=1): print ' in the test arg-is%s '%n decorartor (test) (' Alex ', x=2)
Non-parametric adorner
Import timedef decorator (func): def wrapper (* Args,**kwargs): start=time.time () func (*args,**kwargs) stop=time.time () print ' run time is %s ' % (stop-start) print timeout return wrapper @decoratordef test (list_test): for i in list_test: time.sleep (0.1) print '-' *20,i #decorator (test) (range) test (Range (10))
2. Parametric decorator
Import timedef timer (timeout=0): def decorator (func): def wrapper (*args,**kwargs): start=time.time () func (*args,**kwargs) stop= Time.time () print ' Run time is %s ' % (stop-start) print timeout return wrapper return decorator@timer (2) def test (list_test): for i in List_test: time.sleep (0.1) print '-' *20,i #timer (timeout=10) (test) (range) test (range (10))
Six: Decorator application case:
Adorner function: function timeout is terminated
# -*- coding: utf-8 -*- from threading import thread Import time class timeoutexception (Exception): pass threadstop = thread._thread__stop# Get private Functions def timelimited (Timeout): def decorator ( function): def decorator2 (*args,**kwargs): class timelimited ( Thread): def __init__ (Self,_error= none,): thread.__init__ (self) self._error = _error def run (self): try: self.result = function (*args,**kwargs) except exception,e: self._error =e def _stop (self): if self.isalive (): threadstop (self) t = timelimited () t.start () t.join (timeout) if isinstAnce (t._error,timeoutexception): t._stop () raise timeoutexception (' timeout for %s ' % ( Repr (function))) if t.isalive (): t._stop () raise timeoutexception (' timeout for %s ' % ( Repr (function))) if t._error is None: return t.result return decorator2 return decorator @ Timelimited (2) def fn_1 (secs): time.sleep (secs) return ' finished ' if __ name__ == "__main__": print fn_1 (4)
This article from "Amin blog" blog, declined reprint!
Python Base 4 Adorner