代码要遵循开放封闭原则
封闭:已实现的功能代码块
开放:对扩展开发

通用装饰器

def set_func(func):
    def call_func(*args, **kwargs):
        return func(*args, **kwargs)
    return call_func

@set_func
def test(*args, **kwargs):
    return ("hahaha", args, kwargs)

print(test(100, 200, mm=100))

带有参数的装饰器

def set_level(level_num):
    def set_func(func):
        def call_func(*args, **kwargs):
            if level_num == 1:
                print("---权限验证1---")
            elif level_num == 2:
                print("---权限验证2---")
            return func()
        return call_func
    return set_func

@set_level(1)
def test1():
    print("---test1---")
    return "ok"

@set_level(2)
def test2():
    print("---test1---")
    return "ok"

ret = test1()
print(ret)
test2()
print(ret)
Last modification:December 31st, 2019 at 06:36 pm
如果觉得我的文章对你有用,请随意赞赏