闭包函数

本文深入探讨了闭包函数的概念及其在编程中的应用,特别是如何利用闭包实现延迟计算,提高代码效率。同时,文章对比了直接传参与闭包函数传值的不同方式,并通过具体示例展示了闭包在解决实际问题中的灵活性。
# _*_ coding: utf-8 _*_
# 闭包函数:
# 闭包的意义:返回的函数对象,不仅仅是一个函数对象,在该函数外还包裹了一层作用域,这使得,该函数无论在何处调用,优先使用自己外层包裹的作用域
# 应用领域:延迟计算(原来我们是传参,现在我们是包起来)

# def outter():
# x=1
# def inner():
# print('from inner',x)
# return inner
#
#
# f=outter()
#
# def foo():
# # print(outter)
# print(f)
# x=111111111111111111111111111111111111 #定义阶段
# f()
# foo()
# 为函数体传值的两种方式
# def foo():
# print('hello %s' %name)
#
# 方式一:直接以参数的形式传入
# def foo(name):
# print('hello %s' %name)
#
# foo('egon')
# foo('egon')
# foo('egon')

# 方式二:闭包函数
# def outter(name):
# # name='egon'
# def foo():
# print('hello %s' %name)
# return foo
#
# f=outter('egon')
# # print(f)
# f()
# f()
# f()
#
# f1=outter('alex')
# f1()
# f1()
# f1()

# pip3 install requests
# import requests

# 问题
# def get():
# response=requests.get(url)
# if response.status_code == 200:
# print(response.text)

# 解决方案一:
# def get(url):
# response=requests.get(url)
# if response.status_code == 200:
# print(response.text)
#
# get('https://www.baidu.com')
# get('https://www.baidu.com')
# get('https://www.baidu.com')

# 解决方案二:

# def outter(url):
# # url='https://www.baidu.com'
# def get():
# response=requests.get(url)
# if response.status_code == 200:
# print(response.text)
# return get
#
# baidu=outter('https://www.baidu.com')
# cnblogs=outter('https://www.cnblogs.com')

转载于:https://www.cnblogs.com/OutOfControl/p/9710517.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值