1、在python中    @函数名 就叫语法糖

2、闭包:

  在函数内部再定义一个函数,并且这个函数用到了外边函数的变量,那么将这个函数以及用到的一些变量称之为闭包。   

def line_conf(a, b):
    def line(x):
        return a*x + b
    return line

# 调用函数line_conf(a,b),返回的是函数名line
# 所以相当于两步,首先:调用line_conf(1,1)得到返回值line, 再把line赋值给line1
line1 = line_conf(1, 1) # line1 = line  line1引用了函数名line

print(id(line1)) #id相同
print(id(line_conf(1,1))

# line1(5)就是 line(5)
print(line1(5)) 

# 结果:6
#里面的函数line()使用了外部函数的变量a,b ,函数line()与a,b形成闭包。完成了y =a*x+b
闭包语法Demo:

 

"""python3"""
def counter(start=0):
    def incr():
        #nonlocal适用于嵌套函数中内部函数修改外部变量的值
        nonlocal start
        # 改变了start的值
        start += 1
        return start
    return incr

c1 = counter(5)
print(c1()) #打印结果为6

"""python2"""
def counter(start=0):
    count=[start]
    def incr():
        count[0] += 1
        return count[0]
    return incr

c1 = closeure.counter(5)
print(c1())  # 6
在内部函数中改变闭包中外部函数的参数

3、装饰器代码通式:

  意义:在不改变原代码的情况下,给函数增加一些新的功能

 1 def set_fun(func):
 2 
 3     def call_fun(*args,**kwargs):
 4         return func(*args,**kwargs)
 5     return call_fun
 6 
 7 @set_fun
 8 def test(a, b):
 9     print(a+b)
10 
11 if __name__ == '__main__':
12   test(1, 2) # 调用函数
13         # 运行结果为 3
View Code

 

posted on 2018-04-08 19:11  Xiao马  阅读(294)  评论(0编辑  收藏  举报