简聊装饰器

2018-05-19  本文已影响0人  梦亦殇灬
image

写代码要遵循开放封闭原则,虽然在这个原则是用的面向对象开发,但是也适用于函数式编程,简单来说,它规定已经实现的功能代码不允许被修改,但可以被扩展,即:
* 封闭:已实现的功能代码块
* 开放:对扩展开发
所以就有了装饰器。。。
大家先来看这样一段代码

def w1(fun):
    def inner(*args,**kwargs):
        print("hello")
        fun(*args,**kwargs)
    return inner
@w1   
#w1 相当于 test = w1(test)
#下面是原来的代码内容
def test(*args,**kwargs):
    print("I'm superman")
test()

这是一个带有参数的装饰器,既没有 改变原来的内容,又加了修饰了内容 “hello”

def w (id):
    def w1(fun):
        def inner(*args,**kwargs):
            if id == 1:
                print("hello")
                fun(*args,**kwargs)
            else:
                print("hi")
                fun(*args,**kwargs)
        return inner
    return w1
@w(1)
def test(*args,**kwargs):
    print("hello")
@w(2)
def test1(*args,**kwargs):
    print("hi")


test()
test1()

这个装器 可以装饰不同的内容,起到不同的装饰效果

不知道你看懂了吗?
没有看懂的话我可以晚上去你家帮你呀!!

上一篇 下一篇

猜你喜欢

热点阅读