Python学习打卡--day28(基础学习:闭包)
2019-05-30 18:03
597 查看
学习参考文档:https://blog.csdn.net/sc_lilei/article/details/80464645
# 三个经典闭包案例 # no 1 闭包函数引用的变量是父函数的参数 def line_conf(a, b): def line(x): return a * x + b return line # 定义两条直线 line_A = line_conf(2, 1) # y=2x+1 line_B = line_conf(3, 2) # y=3x+2 # 打印x对应y的值 print(line_A(1)) # 3 print(line_B(1)) # 5 # no 2 闭包函数引用的变量时父函数作用域的变量 def lin_conf(): a = 1 b = 2 def line(x): print(a * x + b) return line line = lin_conf() print(line.__closure__) for i in line.__closure__: # 打印引用的外部变量值 print(i.cell_contents) # 1 ; #2 # no 3 def _line_(a, b): def line_c(c): def line(x): return a * (x ** 2) + b * x + c return line return line_c print(_line_(1, 2))
闭包可保存运行环境
# 闭包保存运行环境 # 使用闭包来实现输入 1 2 3,函数并未保存变化的外部变量 _list = [] for i in range(3): def func(a): return i + a _list.append(func) for f in _list: print(f(1)) # 3 3 3 # 引入闭包,可以保存运行环境中的变量 _list = [] for i in range(3): def func_count(i): def func(a): return i + a return func _list.append(func_count(i)) for f in _list: print(f(1)) # 1 2 3
相关文章推荐
- Python学习打卡--day31(基础练习:Python 字符串常用方法)
- Python学习打卡--day34(基础练习: Python list 常用操作)
- Python学习打卡--day29(基础学习:闭包例子)
- Python学习打卡--day31(基础练习:calendar库)
- Python学习打卡--day29(基础学习:匿名函数lambda)
- Python基础学习 -- 列表与元组
- <<Python基础教程>>学习笔记 | 第05章 | 条件、循环和其他语句
- Python基础学习:内置函数(6)
- Python 基础语法学习笔记
- Python基础学习-Django基础
- python 基础学习(字典对象,set对象)
- python学习(1)python基础、数据类型和变量
- Python初学者(零基础学习Python、Python入门)常见问题:书籍推荐、资料、社区
- 【Python学习】python学习手册--第十六章 函数基础
- 2018年11月11日学习心得(python基础)
- Python学习入门基础教程(learning Python)--2.3.3Python函数型参详解
- 【Day 5】Python 基础学习
- python学习之基础语法(其四)
- python 基础学习2
- python中计时工具timeit模块的基本用法 分类: python python基础学习 2013-08-08 10:05 2072人阅读 评论(0) 收藏