tangbinde 发表于 2018-8-11 08:37:19

python 高阶函数详解。

  1,概念: Iterable 和 Iterator
  Iterable 表示该变量可以被 for in 进行迭代。
  Iterator 表示该变量可以被next(o)进行迭代
  (上一个表示有限迭代,下一个表示一个惰性的迭代概念,可以无限迭代。)
  一般的Iterable 的变量有:
  L=[{},[],(1,),{3:4},{3,4}]
  for x in L:
  print(isinstance(x,Iterable))
  print(isinstance(x,Iterator))
  true
  false
  可见,基础变量
  List,tuple,set,dict 都是Iterable,但是 非Iterator.
  Iterator 变量的产生方法有:
  1,使用Iter(Iterable)的方式将Iterable->Iterator
  2,使用生成器:
  L=(x for x in L) 生成Iterator.
  3,使用yield 将函数变成一个Iterator.
  4, 使用map(f(x),Iterable)将其变为Iterator。
  使用list(Iterator)可以将其变为列表。
  高阶函数:
  map:形式 map(f(x),Iterable) return a Iterator.f(x)需要返回值。
  reduce:形式 reduce(f(x,y),Iterable. 进行不断的变量减少,返回所需值。
  reduce 的函数需要在接收两个参数时能正确运行(即只允许两个位置参数)
  filter:形式filter(f(x),Iterable)return a Iterator,f(x)返回true,false。
  sorted(Iterable,key=func,reverse=false 返回Iterable.
  对于Iterator ,其内部被转换为了list.
  Iterator 生成器,是一个工具。其通过方法next(o)进行不断迭代产生数据。
  也可以使用 for,list,....隐式调用next(o)来生成一个list...
  函数的闭包:
  def func()
  def in_func()
  

      return xx  return in_func
  

  对于闭包函数首先:
  1,[]类型变量直接全局有效。
  2,对于int...非全局有效,需要加上nonlocal int ,不然会有一个分配错误。
  使用闭包函数可以纪录该函数本身的信息,比如被调用次数。。等等。
  此时,最好将该函数变更为一个对象。
  例子:
  

  def sumManager():
  count=0
  def thisCount():
  nonlocal count
  count=count+1
  return count
  def thissum(*L):
  s=0
  for x in L:
  s=s+x
  return s
  return
  sumCount,thissum=sumManager()
  print(thissum(1,2,3),sumCount())
  其中,1,使用nonlocal or []指定母函数中的变量可以被子函数访问。
  2,两个函数需要同时返回,这样他们指向同一个函数体变量。
  匿名函数:lambda x,y: 表达式,返回值就是表达式的值。
  L=(lambda x,y:x+y)(3,4)
  L=list(map(lambda x: x*x,))
  L=list(filter(lambda x:x%2==1,range(1,100)))
  Decorator:装饰器,用于修饰函数。
  1,func---本身是一个对象:所以具备对象属性:比如func.name
  2,func---全参数调用:func(*args,kw)所有函数都可以支持这个参数表。
  3,Decorator 的常见形式:
  def log(f):
  functools.wraps(f)
  def wrapper(*args,*kw):
  act1
  t=f(args,kw)
  act2
  return t
  return wrapper
  

    4,带参数类型:  def log(para):
  def decorator(fun):
  functools.wraps(fun)
  def wrapper(*args,**kw):
  act1
  t=fun(*args,**kw)
  act2
  return t
  return wrapper
  return decorator
  def log(para):
  

  if isinstance(para,str):
  def decorator(f):@functools.wraps(f)br/>else:
  @functools.wraps(para)
def wrapper(k,kw):
  print('begin')
  sv=para(*k,**kw)
  print('end')
  return sv
  return wrapper
  

         也可以使用如下的办法:  def log(para):
  def decorator(func):
  def warpper(*args,**kw):
  sv=func(*args,**kw)
  return sv
  return warpper
  if isinstance(para,str):
  return decorator
  else:
  return decorator(para)
  

  ---------------------相当简洁有效。
  

  偏函数
  import functools
  

  >> int2 = functools.partial(int, base=2)

页: [1]
查看完整版本: python 高阶函数详解。