Reference:
http://blog.csdn.net/marty_fu/article/details/7679297(闭包,推荐看这个)https://foofish.net/python-decorator.html(装饰器,推荐)http://www.cnblogs.com/tqsummer/archive/2010/12/27/1917927.html(yield)http://www.cnblogs.com/longdouhzt/archive/2012/05/19/2508844.html(特殊语法,lambda、map等)
1. Closures:
python中的闭包从表现形式上定义(解释)为:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)
Example:
In [3]: def f1(x): ...: def f2(y): ...: return x + y ...: return f2 ...: In [4]: func=f1(6)In [5]: func(9)Out[5]: 15在f1内定义了f2,但f2函数引用了f1中的变量x,f1返回了f2的函数名,当对func进行赋值的时候,同时也对x赋值了,func函数调用的是f2的函数,而却能记住x的值
2. Adorner:
装饰器跟闭包的语法类似,差别在于,它必须传递一个函数,而后又在内部函数中对这个函数进行引用(因为装饰器存在的意义就是增强传递过来的函数的功能)
Example:
In [9]: def f1(func):
...: Def wrapper ():
...: print "Now,begin Your Show:"
...: func ()
...: print "the show is over."
...: Return wrapper
...:
In [10]: @f1 ...: def f2(): ...: print "haha,i am no 1" ...: In [11]: f2()now,begin your show: haha,i am no 1the show is over.在这里@f1的效果相当于 f2=f1(f2) ,如果这么做的话,f2要先定义
3.yield
yield用来模拟生成器的工作过程,它会在条件内生成值,遇到下一个yield就停止等待值被取走然后再生成下个值,直到条件不满足(这个我不确定,大概是这个过程,等我查资料再确定)
Example:
In [39]: def g(n):...: i=0...: while i < n : ...: yield i...: i+=1...: In [40]: t=g(3)In [41]: type(t)Out[41]: generatorIn [42]: t.next()Out[42]: 0In [43]: t.next()Out[43]: 1In [44]: t.next()Out[44]: 2In [45]: t.next()---------------------------------------------------------------------------StopIteration
The following are excerpts from: http://www.cnblogs.com/longdouhzt/archive/2012/05/19/2508844.html
A lambda expression returns a function object
Example:
func = lambda x,y:x+yfunc相当于下面这个函数def func(x,y): return x+y
Note that DEF is a statement and lambda is an expression
In this case, you can only use lambda, not def.
[(lambda x:x*x)(x) for x in range(1,11)]
The function in Map,reduce,filter can be generated using lambda expressions!
map(function,sequence)
Pass the worth parameter in the sequence to function, and return a list containing the result of the function execution.
If function has two parameters, that is, map (FUNCTION,SEQUENCE1,SEQUENCE2).
Example:
Request 12,33,44
map(lambda x:x*x,range(1,5))
The return value is [1,4,9,16]
Reduce (function,sequence)
function can receive only 2 of the number of arguments
The first value and the second worth parameter are passed to function in sequence, and the return value of function and the third worth parameter are passed to
function, and then returns only one result.
Example:
Add 1 to 10 of the cumulative
reduce(lambda x,y:x+y,range(1,11))
The return value is 55.
Filter (Function,sequence)
The return value of function can only be true or false
The values in the sequence are passed to function individually, and if the return value of function (x) is true, the X is added to the return value of the filter. In general, the return value of filter is list, special cases such as sequence is a string or tuple, then the return value is the type of sequence.
Python closures, adorners, and Lambda (notes)