zoukankan      html  css  js  c++  java
  • 闭包实用

    # lst=['德玛西亚','诺克萨斯','暗影岛','班德尔城']
    # print('__iter__' in dir(lst))
    # print(dir(lst))
    # it=lst.__iter__()
    #模拟if
    # while 1:
    #     try:
    #         name=it.__next__()
    #         print(name)
    #     except StopIteration:
    #         break
    # def fn():
    #     print("英雄联盟")
    # a=fn
    # print(fn())#不存在return会输出None
    # print(fn)
    # print(a)
    #
    # def f1():
    #     print("德玛西亚")
    # def f2():
    #     print("诺克萨斯")
    # def f3():
    #     print("班德尔城")
    # def f4():
    #     print("暗影岛")
    # lst=[f1,f2,f3,f4,]
    # for i in lst:
    #     i()
    # lst1=[f1(),f2(),f3(),f4()]
    # print(lst1)
    # 闭包:在内层函数中调用了外层函数的变量  好处:1.常住内存  2.安全,防止被其他程序改变这个变量
    # def fn():
    #     name="lol"
    #     def fn1():
    #         print(name)
    #     print(fn1.__closure__)#检测闭包是否存在该函数中,若存在输出内存地址,若不存在输出为空
    #     return fn1
    # ret=fn()
    # ret()
    #爬虫中的闭包:
    # from urllib.request import urlopen
    # def but():
    #     content = urlopen("http://www.h3c.com/cn/").read()
    #     def inner():
    #         print("你好啊")
    #          # return content # 在函数内部使用了外部的变量 . 闭包
    #     print(inner.__closure__)    # 查看inner是否是闭包, 如果有东西就是闭包, 没东西就不是闭包
    #     return inner
    # print("加载中........")
    # fn = but()  # 这个时候就开始加载校花100 的内容
    # # 后⾯需要⽤到这⾥⾯的内容就不需要在执⾏⾮常耗时的⽹络连接操作了
    # content = fn()   # 获取内容
    # print(content)
    # content2 = fn()  # 重新获取内容
    # print(content2)
    # print(isinstance(it, Iterable)) # 判断是否是可迭代的 迭代器一定是可迭代的
    # print(isinstance(it, Iterator)) # 迭代器里面一定有__next__(), __iter__()
    # print("__iter__" in dir(lst))   # 确定是一个可迭代的
    # print("__next__" in dir(lst))   # 确定不是一个迭代
    # 迭代器的特点:
    # 1.节省内存空间
    # 2.惰性机制
    # 3.只能向前,不能相反
    # from collections import Iterable,Iterator
    # lst=['德玛西亚','诺克萨斯','暗影岛','班德尔城']
    # it=lst.__iter__()
    # print(isinstance(it, Iterator))
    # print(isinstance(lst,Iterable))
    # # while 1:
    # #     try:
    # #         name=it.__next__()
    # #         print(name)
    # #     except StopIteration:
    # #         break
    
  • 相关阅读:
    3.无重复字符的最长字串
    k-近邻算法(KNN)
    决策树
    解决anaconda与pycharm冲突导致import无法使用
    2.两数相加
    1.两数之和
    数学建模第七章 数理统计
    数学建模第六章 微分方程建模
    Web(4)servlet
    阿里云卸载自带的JDK,安装JDK完成相关配置
  • 原文地址:https://www.cnblogs.com/zhangdaye/p/9325870.html
Copyright © 2011-2022 走看看