python_函数进阶2

一、函数名的 应用

1、函数名就是函数的内存地址

  def fun():

    pass

  print(fun)

2、函数名可以作为变量

  def fun():

    print('aaa')

  c = fun

  c()

3、函数名作为函数的参数

  def fun():

    print('xx')

  def index(x)

    x()

  index(fun)

4、函数名可以作为函数的返回值

  def foo():

    def inner():

      print('inner')

    return inner

  c = foo()

  c = ()

5、函数名可以作为容器类型的元素

  dic = {'foo':foo,'bar':bar}

  def foo():

    print('foo')

  def bar():

    print('bar')

  for i in dic:

    dic[i]()

 

二、globals与locals

1、globals():不管在任何位置返回的都是全局变量的一个字典

2、locals():返回的是当前位置的变量的一个字典

 

三、闭包函数

1、定义:内部函数对外部作用域变量(非全局变量)的引用,并返回,就是闭包函数

2、__closure__判断是不是闭包

def fun():

  name = 'zs'

  def inner()

    print(name)

  print(inner.__closure)

  return inner

3、闭包作用:

  当程序执行时,遇到函数调用,就会在内存开辟一个空间,局部命名空间,如果这个函数内部形成了闭包,那么

  它不会随着函数的结束而消失

 

四、迭代器

1、可迭代对象:iterable

  对象内部含有__iter__方法就是可迭代对象

  str,dict,list,set,tuple,range  等等

2、dir():查看对象的所有方法

3、判断是不是可迭代对象

  '__iter__'  in  dir()

  from collections import Iterable

    from collections import Iterator

  print('cc',isinstance(Iterable))  #判断是不是可迭代对象

     print('cc',isinstance(Iterator))  #判断是不是迭代器

4、可迭代对象满足可迭代协议

  对象内部含有__iter__  且含有__next__方法就是迭代器

5、可迭代对象转为迭代器

  name = 'zs'

  ite = name.__iter__

  ite = iter(name)

6、迭代器的与可迭代对象区别:

  可迭代对象不能取值,迭代器是可以取值的(__next__)

  迭代器节省内存

  迭代器是单向的,不反复

  迭代器每次只取一个值

7、dic = {'name':'zs','age':'18'}

  ite = dic.__iter__

  while 1:

    try:

      print(ite.__next__)

    except StopIteration:

      break 

 

  

posted on 2018-08-17 17:08  旧巷子里的猫  阅读(139)  评论(0编辑  收藏  举报