当前位置:主页 > 软件编程 > Python代码 >

Python的闭包和装饰器你真的了解吗

时间:2022-06-07 09:21:47 | 栏目:Python代码 | 点击:

闭包

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

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>

总结

您可能感兴趣的文章:

相关文章