zoukankan      html  css  js  c++  java
  • 闭包

    # closure:闭包
    # 闭包:定义在函数内部的函数,这个内部的函数就是闭包

    # 应用场景:
    # 1.可以去使用其他函数的内部变量,且还可以保证调用位置不变(闭包的函数对象作为那个函数的返回值)
    def outer():
    count = 3000
    def fn():
    print(count) # 能使用outer内部的变量count
    return fn
    # 还是在外界调用
    outer()() # outer()() => fn() => 调用fn

    # 2.延迟执行(外层函数可以为内存函数传递参数)
    import requests

    # def show_html(url):
    # response = requests.get(url)
    # print(response.text)
    #
    # show_html('https://www.baidu.com')
    # show_html('https://www.baidu.com')
    # show_html('https://www.sina.com.cn')

    def outer(url):
    def show_html():
    response = requests.get(url)
    print(response.text)
    return show_html
    # 制作 爬百度与新浪的 函数对象
    show_baidu = outer('https://www.baidu.com')
    show_sina = outer('https://www.sina.com.cn')
    # 延迟到需求来了,需要爬百度,就用百度函数对象,需要爬新浪,就用新浪函数对象
    show_baidu()
    show_sina()
    show_baidu()
  • 相关阅读:
    如何配置MySQL
    软件工程第三次作业
    软件工程第二次作业
    软件工程第一次作业
    Python 【面试总结】
    Vue【你知道吗?】
    Python 【面试强化宝典】
    Python 【基础面试题】
    Vue 【前端面试题】
    Redis 【常识与进阶】
  • 原文地址:https://www.cnblogs.com/qiangyuzhou/p/10787405.html
Copyright © 2011-2022 走看看