zoukankan      html  css  js  c++  java
  • 闭包、迭代器

    1.函数名
    函数名就是变量名(可以进行赋值),函数名存储的是函数的地址
    需要括号才可以执行
     
    2.闭包:内层函数对外层函数(非全局)变量的引用
    作用:1.保护一个变量,让他不受改变
    2.让一个变量常驻内存
    使⽤__closure__来检测函数是否是闭包. 使⽤函数名.__closure__返回cell就是
    闭包. 返回None就不是闭包
     
    3.Iterable (可迭代的)
    Iterator(迭代器)
    d7ir() 查看变量能够执行的方法(内置函数)
    dir(str)) # 查看str能够执行的操作. 内部的方法
     
    list = [1,2,3,4,5,6]
    it = list._iter_()
    while 1:
    try:
    aa = it._next_()
    print(aa)
    except StopIteration:
    break
     
    如何判断一个数据是否是可迭代对象
    1. dir() -> __iter__ 可迭代的
    dir() -> __next__ 迭代器
    lst = ["秦始皇", "汉武帝", "孝文帝", "隋炀帝", "李世民"]
    print("__iter__" in dir(lst)) # True 可迭代的
    print("__next__" in dir(lst)) # False 不是迭代器
     
    from collections import Iterable(可迭代的), Iterator(迭代器)
    print(isinstance(lst, Iterable)) # True
    print(isinstance(lst, Iterator)) # False
     
    print(isinstance({1,2,3}, Iterable)) # True, 可以使用for循环
    迭代器特点:1.节省内存
    2.惰性机制(不给_next_不给值)
    3.只能往前,不可以重复

  • 相关阅读:
    二维vector初始化
    分类、目标检测、语义分割、实例分割的区别
    天池博客链接
    Windows pycocotools 安装
    解决 windows下pd.read_csv()读取文件失败
    解决 Anaconda中已有库 notebook却无法import
    win10下 修改Jupyter Notebook的默认路径
    C++ stack操作
    nginx启动错误
    Selenium的PageObject模式
  • 原文地址:https://www.cnblogs.com/v-h3/p/9887219.html
Copyright © 2011-2022 走看看