Python设计模式:修饰器模式

设计模式六:修饰器模式

什么是修饰器模式

以透明的方式动态地将功能添加到一个对象中

给对象添加额外功能的方法

1.直接将功能添加到对象所属的类,
2.使用组合
3.使用继承
4.使用修饰器

典型案例

图形用户界面工具集,希望给单个组件/部件添加一些特性,比如滚动 颜色 阴影

实例代码

import functools
def add_color(fn):
    #要保留被修饰函数的文档和签名,可以用wraps来修饰
    @functools.wraps(fn)
    #这里是执行修饰函数
    def add_colors(args):
        if args != '':
            #执行被修饰函数
            print(fn(args))
            return '{}`s color is blue '.format(args)
    return add_colors

@add_color
def show(s):
    s = 'apple'
    return s

if __name__ == "__main__":
    a = show('pen')
    print(a)
发布了23 篇原创文章 · 获赞 2 · 访问量 1051

猜你喜欢

转载自blog.csdn.net/youngdianfeng/article/details/103774507