码迷,mamicode.com
首页 > 编程语言 > 详细

python --闭包学习

时间:2016-01-25 11:24:40      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

闭包概念:

Closure:内部函数中对enclosing作用域的变量进行引用

enclosing作用域:函数内部与内嵌函之间

范例1:

#coding:utf-8

def set_passline(passline):
    def cmp(val):
        if val>= passline:
            print "passline is %d"%passline
            print "%d is pass"%val
        else:
            print "passline is %d"%passline
            print "%d is failed"%val
    return cmp


f_100=set_passline(60)
f_150=set_passline(90)

f_100(89)
f_150(89)

 输出:

passline is 60
89 is pass
passline is 90
89 is failed

范例2:

 

#coding:utf-8
def my_sum(*arg):
    return sum(arg)
def my_average(*arg):
    return sum(arg)/len(arg)

def dec(func):
    def in_dec(*arg):
        print (in_dec arg=,arg)
        if len(arg)==0:
            return 0
        for val in arg:
            if not isinstance(val,int):
                return 0
        return func(*arg)
    return in_dec

my_sum=dec(my_sum)
my_average=dec(my_average)
print my_sum(1,2,3,4,5)
print my_sum(1,2,3,4,5,6)
print my_average(1,2,3,4,5)
print my_average()

 

输出:

(‘in_dec arg=‘, (1, 2, 3, 4, 5))
15
(‘in_dec arg=‘, (1, 2, 3, 4, 5, ‘6‘))
0
(‘in_dec arg=‘, (1, 2, 3, 4, 5))
3
(‘in_dec arg=‘, ())
0

 

闭包作用

1:封装

2:代码复用

python --闭包学习

标签:

原文地址:http://www.cnblogs.com/saryli/p/5156624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!