装饰器,lambda,map,reduce

Posted by tzwlwy's Blog on July 3, 2018

装饰器

@deco1(deco_arg)
@deco2
def func(): pass
This is equivalent to:这等价于
func = deco1(deco_arg)(deco2(func))

匿名类

a=lambda x, y=4: x + y  #x,y=4 为定义的变量 ,:后面表示匿名类函数的执行情况
a(3)  #return  7

x = 10
def foo():
    y = 5
    bar = lambda :x+y
    print(bar())
foo()  #15

x = 10
def foo():
    y = 5
    bar = lambda :x+y
    print(bar)
foo()  #<function foo.<locals>.<lambda> at 0x021B2198>


x = 10
x = 10
def foo():
    y = 5
    bar = lambda y=y: x+y
    print (bar())
    y = 8
    print(bar()) #这边bar()的值为18,因为lambda 的定义没有变。


#这么写就好了
x = 10
def foo():
   y = 5
   bar = lambda z:x+z
   print (bar(y))
   y = 8
   print(bar(y))
foo()

a=map((lambda x: x+2), [0, 1, 2, 3, 4, 5])  #返回一个iterator ,相当于a=iter((2,3,4,5,6,7))
map(lambda x, y: (x+y, x-y), [1,3,5], [2,4,6])  #一个例子了解map和匿名类结合
#iter可以使用next(a)来获取并释放a[0]
from functools import reduce
a=reduce((lambda x,y: x+2*y), range(4))
#x=0,y=1
#x=2,y=2
#x=6,y=3
#类似递归