[b0019] python 归纳 (五)_类装饰器

总结:
类装饰器, 本质是一个函数,输入一个类,返回一个类

 

Case 1 啥都没做

def deco(in_class):
    return in_class

@deco
class Cat:
    def __init__(self,age):
        print "flag1"
        self.age = age
        print "flag11"

    def display(self):
        print "flag2"
        print(self.age)
        print "flag21"

if __name__ == '__main__':

    c = Cat(12)
    print "----------"
    c.display()

"""
Out:

flag1
flag11
----------
flag2
12
flag21

"""

 

Case2 

def deco(in_class):
    class NewClass:
        def __init__(self,age,color):
            print "flag3"
            self.wrapped = in_class(age)  # 实例原来的类
            self.color  = color
            print "flag31"

        def display(self):
            print "flag4"
            print(self.color)
            print(self.wrapped.age)
            print "flag41"
    return NewClass

@deco
class Cat:
    def __init__(self,age):
        print "flag1"
        self.age = age
        print "flag11"

    def display(self):
        print "flag2"
        print(self.age)
        print "flag21"

if __name__ == '__main__':

    c = Cat(12,'black')
    print "----------"
    c.display()

"""
Out:

flag3
flag1
flag11
flag31
----------
flag4
black
12
flag41
"""

 

posted @ 2018-08-31 08:17  sunzebo  阅读(202)  评论(0编辑  收藏  举报