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/

  • 相关阅读:
    Running ASP.NET Applications in Debian and Ubuntu using XSP and Mono
    .net extjs 封装
    ext direct spring
    install ubuntu tweak on ubuntu lts 10.04,this software is created by zhouding
    redis cookbook
    aptana eclipse plugin install on sts
    ubuntu open folderpath on terminal
    ubuntu install pae for the 32bit system 4g limited issue
    EXT Designer 正式版延长使用脚本
    用 Vagrant 快速建立開發環境
  • 原文地址:https://www.cnblogs.com/space007/p/5953980.html
Copyright © 2011-2022 走看看