码迷,mamicode.com
首页 > 编程语言 > 详细

Python的装饰器

时间:2017-09-22 17:51:40      阅读:185      评论:0      收藏:0      [点我收藏+]

标签: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


本文出自 “小鱼的博客” 博客,谢绝转载!

Python的装饰器

标签:ja

原文地址:http://395469372.blog.51cto.com/1150982/1967814

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!