标签:ja
装饰器模式:通过一个类来修改一个类
实例一:
#!/usr/bin/env python #coding:utf-8 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): print ‘be keep‘ #添加了新动作 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()
结果:
Source fun. keep fun. Start ... Source fun. be keep keep fun.
实例二: #!/usr/bin/env python #coding:utf-8 class Water: def __init__(self): self.name=‘Water‘ def show(self): print self.name ‘改类启到装饰的作用‘ class Deco: #def show(self): # print self.name pass ‘Deco 只是一个占位符而已,启动传递参数的作用‘ 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() a=Salt(w) a.show()
结果:
Sugar Water Salt Water
实例三: #!/usr/bin/env python #coding:utf-8 ‘‘‘ 装饰器模式可以不以继承的方式而动态修改类的方法 装饰器模式可以不以继承的方式返回一个被修改的类 ‘‘‘ ‘类装饰器‘ def deco(a_class): class NewClass: def __init__(self,age,color): self.wrapped=a_class(age) self.color=color def display(self): print ‘call here‘ print self.color print self.wrapped.age return NewClass @deco class Cat: def __init__(self,age): self.age=age #def display(self): # print ‘no called here‘ # print(self,age) if __name__==‘__main__‘: c=Cat(12,‘black‘) c.display()
结果:
call here black 12
本文出自 “小鱼的博客” 博客,谢绝转载!
标签:ja
原文地址:http://395469372.blog.51cto.com/1150982/1967814