Python 装饰器模式

# -*- coding: utf-8 -*-
"""
Created on Sat Feb 24 11:37:17 2018

@author: mz
"""

class Warrior:
    def __init__(self):        
        self.attrack = 100
        self.defend = 200   
        
    def ShowAttributes(self):
        print("*self*")
        print("attrack : %d" % (self.attrack) )
        print("attrack : %d \r\n" % (self.defend) )
        

class OnCloth(Warrior):
    def __init__(self, rhs):
        self.attrack = 100+ rhs.attrack
        self.defend  = 300+ rhs.defend
    
    def ShowAttributes(self):
        print("*on cloth*")
        print("attrack : %d" %(self.attrack))
        print("attrack : %d \r\n" %(self.defend) )
    
        
class OnWeapon(Warrior):
    def __init__(self, rhs):
        self.attrack = 1500 + rhs.attrack
        self.defend  = 100  + rhs.defend
    
    def ShowAttributes(self):
        print("*on weapon*")
        print("attrack : %d " %(self.attrack))
        print("attrack : %d \r\n" %(self.defend))

if "__main__" == __name__:
    print("crete a warrior....")
    person = Warrior()
    person.ShowAttributes()
    
    print("put on cloth....")
    putonCloth = OnCloth(person);
    person.ShowAttributes();
    putonCloth.ShowAttributes();
    
    print("put on weapon....")
    holdWeapon = OnWeapon(putonCloth);
    person.ShowAttributes();
    putonCloth.ShowAttributes();
    holdWeapon.ShowAttributes();

装饰模式,经过装饰后总的属性发生变化,但是本身属性不发生变化, 输出结果:

crete a warrior....
*self*
attrack : 100
attrack : 200 

put on cloth....
*self*
attrack : 100
attrack : 200 

*on cloth*
attrack : 200
attrack : 500 

put on weapon....
*self*
attrack : 100
attrack : 200 

*on cloth*
attrack : 200
attrack : 500 

*on weapon*
attrack : 1700 
attrack : 600 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值