浅から深まで、Python装飾器に入る---第四編:進級--関数装飾類


下一篇:浅入深,进入Python装饰器----第三篇:进阶--类装饰関数
かんすうかざり
@  
 
            ,            ,            ,    ,                    .
####   :                          

3.1関数装飾器で元のクラスを拡張する
def KuoZhan(cls):
    def new_func():
        print("       new_func")
    def new_class():
        cls.say = "       "
        cls.new_func = new_func
        #      ,   3.2            , 
        return cls
    return new_class
#                   
@KuoZhan        #1.  @KuoZhan ==> KuoZhan( )                                                                       
class MyClass():
    def func():
        print("        func")
#             ,    MyClass         
# type(MyClass) = 
obj = MyClass()
# obj       new_class    cls
obj.func()
obj.new_func()
print(obj.say)

>>>        func
>>>       new_func
>>>       

3.2関数装飾器で元のクラスを拡張する
def KuoZhan(cls):
    #     self
    def new_func(self):
        print("       new_func")
    def new_class():
        cls.say = "       "
        cls.new_func = new_func
        #       
        return cls()
    return new_class
#                   
@KuoZhan        #1.  @KuoZhan ==> KuoZhan( )                                                                       
class MyClass():
    #     self
    def func(self):
        print("        func")
#             ,    MyClass         
# type(MyClass) = 
obj = MyClass()
# obj       new_class    cls
obj.func()
obj.new_func()
print(obj.say)

>>>        func
>>>       new_func
>>>       

3.3パラメータ付き関数装飾器で元のクラスを拡張する
def outer(n):
    def KuoZhan1(cls):
        def new_func():
            print("       new_func")
        def new_class():
            cls.say = "       "
            cls.new_func = new_func
            #      ,   3.2            , 
            return cls
        return new_class
    def KuoZhan2(cls):
        pass
    if n == 1:
        return KuoZhan1
    else:
        return KuoZhan2

#                   
@outer(1)        #1. outer(1) ==> KuoZhan1   2.@out(1) == @KuoZhan1                                                                        
class MyClass():
    def func():
        print("        func")
#             ,    MyClass         
# type(MyClass) = 
obj = MyClass()
# obj       new_class    cls
obj.func()
obj.new_func()
print(obj.say)

>>>        func
>>>       new_func
>>>