zoukankan      html  css  js  c++  java
  • python基础之闭包与迭代器

    一、闭包

    1.写法:在外层函数中声明一个变量,在内存函数使用或者返回这个变量。

    这个结构叫闭包。

    def fun1():
        a=10
        def fun2():
        print(a)
    return fun2

    这种结构就叫做闭包

    2.作用:

    1).保护变量

    2).使变量常驻内存

    __closure__:有东西,就是闭包;None就不是闭包

    def outer():
        a = 10 # 常驻内存
        def inner():
            print(a) # 在内部使用的外面的变量
        return inner # 返回了内部函数
    ret = outer()
    print(ret.__closure__) # 有东西, 就是闭包. None就不是闭包
    打印结果:(<cell at 0x03831310: int object at 0x5073E840>,)

    二、迭代器

    迭代器:

    1.Iterable 可迭代的对象,里面包含了__iter__(),可以使用for循环

    包括str,list,tuple,dict,set,open(),range()

    2.Iterator:迭代器,里面包含了__iter__()和__next__(),也可以使用for循环

    3.dir() 查看某数据类型中可以执行的方法

    lst = [1,2,3,4]
    print(dir(lst))

    4.从那么多个方法里面找'__iter__'太难了,用下面这个判断有没有这个方法

    lst = [1,2,3,4]
    it = dir(lst)
    print('__iter__' in it)

    5.总结特点

    1)节省内存

    2)惰性机制:只有执行__next__()才执行

    3)只能向前,不能反复

    6.用while实现for循环

    lst = [1,2,3,4]
    it = lst.__iter__()
    while 1:
        try:
            print(it.__next__())
        except StopIteration:
            print('结束了')
            break
    for el in lst:
        print(el)
    else:
        print('结束了')
     
    lst = [1,2,3]
    it = dir(lst)
    print('__next__' in it)
    print(it)
    from collections import Iterable # 可迭代的            
    from collections import Iterator # 迭代器             
                                                       
    lst = ["周润发","麻花藤","刘刘刘"]                           
    print(isinstance(lst, Iterable)) # instance  实例, 对象
    print(isinstance(lst, Iterator)) # instance  实例, 对象
                                                       
    it = lst.__iter__()                                
    print(isinstance(it, Iterable)) # instance  实例, 对象 
    print(isinstance(it, Iterator)) # instance  实例, 对象 
  • 相关阅读:
    页面整体布局思路
    CSS3转换、过渡、动画效果及css盒子模型
    CSS随笔
    CSS基础,认识css样式
    HTML基础表单
    HTML基础
    java.sql.SQLException: 调用中无效的参数DSRA0010E: SQL 状态 = null,错误代码 = 17,433
    There is no Action mapped for namespace / and action name accredit.
    myeclipse开启后卡死、building workspace缓慢 问题解决
    you need to upgrade the working copy first
  • 原文地址:https://www.cnblogs.com/doit9825/p/13081154.html
Copyright © 2011-2022 走看看