python 闭包
2016-01-25 15:02
507 查看
# -*- coding:gb2312 -*- __author__ = 'liuyc' # 01:闭包用例 def setPassLine(line): ''' 这是一个引用自由变量的函数,他会与cmp这个函数同在。 但是它不是保存在代码中,而是保存在line_60函数的属性中。 ''' # cmp函数相当于一个包 def cmp(score): if score >= line: print 'pass...' else: print 'fail...' return cmp line_60 = setPassLine(60) # 设置60分为及格线 line_60(60) line_85 = setPassLine(85) # 设置85分为及格线 line_85(60) # 02:闭包作用:封装和代码复用 def my_sum(*args): return sum(args) def my_average(*args): return sum(args) / len(args) def closure(func): def in_closure(*args): if len(args) == 0: return 0 for val in args: if not isinstance(val, int): return 0 return func(*args) return in_closure my_sum = closure(my_sum) # closure(my_sum)-> (直接到return in_closure) -> my_sum print my_sum(1,2,3,4)
相关文章推荐
- Python延迟打印字符
- Python 多线程编程threading模块
- python中函数参数,函数调用参数传递,可变参数,*expression,**expression
- python算法——第四天
- Python基本语法
- Python――几款流行ORM框架(SQLAlchemy ,Django ORM)
- python多线程与多进程 超简单使用
- 基于python unitest架构的接口自动化监控
- 使用python打印所有汉字
- Python常用lib
- Python获取目录、文件的注意事项
- 45. Jump Game II leetcode python 2016 new season
- Python 基础【二】 上
- 《Python项目开发实战》--熟悉Python基础后我能做什么?
- python分布式进程
- Python -- collection 系列
- Python 字符编码学习-ascii编码,Unicode和UTF-8之间的关系
- Python开发基础-day2
- Python 基础教程
- Python 爬虫入门(二)—— IP代理使用