Advanced a python (functional programming) [2-8] python decorator the decorator

No parameter written in python decorator

The decorator nature of Python is a higher-order functions, it receives a function as a parameter, and then returns a new function .

Use @ decorator syntax provided in Python, to avoid hand written f = decorate (f) such code.

Consider a @log definition:

. 1  DEF log (f): # write a decorator, essentially a higher-order function, a receiving function (f) as a parameter, and then returns a new function Fn 
2      DEF Fn (X):
 . 3          Print  ' Call ' + F. the __name__ + ' () ... ' # enables the printing function call 
. 4          return F (X) # returns a function for f (x), only one parameter X 
. 5      return Fn # return a new function

For the factorial function, @ log work well:

1 @log
2 def factorial(n):
3     return reduce(lambda x,y: x*y, range(1, n+1))
4 print factorial(10)

result:

call factorial()...
3628800

However, the argument is not a function of the call will be given:

@log
def add(x, y):
    return x + y
print add(1, 2)

result:

1 Traceback (most recent call last):
2   File "test.py", line 15, in <module>
3     print add(1,2)
4 TypeError: fn() takes exactly 1 argument (2 given)

Because the  add () function takes two arguments, but @log write a function that returns the dead with only one parameter .

@Log make any adaptive function defined parameters may be utilized in the Python  * args and ** kW , arbitrary number of arguments always ensure normal call:

1 def log(f):
2     def fn(*args, **kw):
3         print 'call ' + f.__name__ + '()...'
4         return f(*args, **kw)
5     return fn

task

Please write a @performance, it can print out the time function calls.

. 1  Import Time
 2  
. 3  DEF Performance (F): # write time a decorator, the printing time for a function call 
. 4      DEF Fn (* args, ** kW): # adaptive define any parameters to ensure that any number of parameter is always normal call 
. 5          T1 = the time.time () # timing before the call 
. 6          R & lt = f (* args, ** kW) # where f is the function to call 
. 7          T2 = the time.time () # call End timing 
. 8          Print  ' Call% S () in% FS ' % (F. the __name__ , (T2- T1))
 . 9          return R & lt # return function 
10      return Fn# Returns a new function Fn 
. 11          
12 is  
13 is  @performance
 14  DEF factorial (n-):
 15      return the reduce ( the lambda X, Y: X * Y, Range (. 1,. 1 n-+ ))
 16  
. 17  Print factorial (10)

 

Guess you like

Origin www.cnblogs.com/ucasljq/p/11622124.html