亲宝软件园·资讯

展开

Python的闭包和装饰器

尤诺. 人气:0

闭包

闭包就是能够读取其他函数内部变量的函数。

def test1(k, b):
    def test1_1(x):
        print(k*x+b)
    return test1_1
t1 = test1(1, 2)
t1(0)
t1(1)
t1(2)

闭包中修改数据

x = 300
def test1():
    x = 200
    def test2():
        nonlocal x
        print("----1----x = {}".format(x))
        x = 100
        print("----2----x = {}".format(x))
    return test2
t1 = test1()
t1()

装饰器

实现对无参数函数的装饰器

def set_func(func):
    def call_func():
        print("装饰器执行")
        func()
    return call_func
@set_func   # 等价于sumNum = set_func(sumNum)
def sumNum():
    print("sumNum")
sumNum()

实现对有参数函数的装饰器

# 对有参数、无返回值的函数进行装饰
def set_func(func):
    def call_func(num):
        print("装饰器")
        func(num)
    return call_func
@set_func
def sumNum(num):
    print("sumNum = {}".format(num))
sumNum(100)

对不定长参数的函数进行装饰

def set_func(func):
    def call_func(*args, **kwargs):
        print("装饰器")
        func(*args, **kwargs)  # 拆包
    return call_func
@set_func
def sumNum(num, *args, **kwargs):
    print("sumNum = {}".format(num))
    print("args = {}".format(args))
    print("kwargs = {}".format(kwargs))
sumNum(100, 200, c=100)

对有返回值的函数进行装饰

def set_func(func):
    def call_func(*args, **kwargs):
        print("装饰器")
        return func(*args, **kwargs)  # 拆包
    return call_func
@set_func
def sumNum(num, *args, **kwargs):
    print("sumNum = {}".format(num))
    print("args = {}".format(args))
    print("kwargs = {}".format(kwargs))
    return "200 ok"
sumNum(100, 200, c=100)

多个装饰器对同一个函数装饰

def add_h1(func):
    def h1():
        h1_str = "<h1>" + func() + "</h1>"
        return h1_str
    return h1

def add_a(func):
    def call_func():
    	a_str = "<a>" + func() + "</a>"
        return a_str
    return call_func

@add_h1
@add_a
def get_str():
    return "haha"
get_str()

输出为:<h1><a>haha</a></h1>

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!   

加载全部内容

相关教程
猜你喜欢
用户评论