zoukankan      html  css  js  c++  java
  • Python装饰模式实现源码分享

    1.一般来说,通过继承可以获得父类的属性,还可以通过重载修改其方法。

    2.装饰模式可以不以继承的方式而动态地修改类的方法。

    3.装饰模式可以不以继承的方式而返回一个被修改的类。

    4.基本实现

    程序演示如下:

    例一:

    13_eg1.py

    class BeDeco:

        def be_edit_fun(self):

            print('Source fun.')

        def be_keep_fun(self):

            print('Keep fun.')

    class Decorater:

        def __init__(self,dec):

            self._dec = dec()

        def be_edit_fun(self):

            print('Start...')

            self._dec.be_edit_fun()

        def be_keep_fun(self):

            self._dec.be_keep_fun()

    if __name__ == '__main__':

        bd = BeDeco()

        bd.be_edit_fun()

        bd.be_keep_fun()

        dr = Decorater(BeDeco)

        dr.be_edit_fun()

        dr.be_keep_fun()

    程序的运行结果为:

    例二:

    13_eg2.py

    class Water:

        def __init__(self):

            self.name = 'Water'

        def show(self):

            print(self.name)

    class Deco:

        def show(self):

            print(self.name)

    class Sugar(Deco):

        def __init__(self,water):

            self.name = 'Sugar'

            self.water = water

        def show(self):

            print(self.name)

            print(self.water.name)

    class Salt(Deco):

        def __init__(self,water):

            self.name = 'Salt'

            self.water = water

        def show(self):

            print(self.name)

            print(self.water.name)

    if __name__ == '__main__':

        w  = Water()

        s = Sugar(w)

        s.show()

        s = Salt(w)

        s.show()

    程序的运行结果为:

    5.类装饰器

    程序演示如下:

    13_eg3.py

    def deco(a_class):

        class NewClass:

            def __init__(self,age,color):

                self.wrapped = a_class(age)

                self.color = color

            def display(self):

                print(self.color)

                print(self.wrapped.age)

        return NewClass

    @deco

    class Cat:

        def __init__(self,age):

            self.age = age

        def display(self):

            print(self.age)

    if __name__ == '__main__':

        c = Cat(12,'black')

        c. display()

    程序的运行结果为:

    原文链接:http://www.maiziedu.com/wiki/python/decorative/

  • 相关阅读:
    http2新特性
    SSL/TLS工作原理
    https工作原理解析
    k8s认证与鉴权
    grpc
    golang channel是线程安全的吗
    golang map是线程安全的吗
    k8s创建deployment的工作流
    Docker实践:部署漏洞扫描 AWVS + Nessus
    Python Peewee
  • 原文地址:https://www.cnblogs.com/space007/p/5953980.html
Copyright © 2011-2022 走看看