zoukankan      html  css  js  c++  java
  • python 装饰器模式

    python 装饰器模式

    前言

    用python学设计模式学的还是学语法居多的感觉,具体的设计模式思想的学习与训练还是看回《Head First:Design Pattern》。

    装饰器模式

    import time
    
    
    def log_calls(func):
        def wrapper(*args, **kwargs):
            now = time.time()
            print(
                "Calling {0} with {1} and {2}".format(
                    func.__name__, args, kwargs
                )
            )
            return_value = func(*args, **kwargs)
            print(
                "Executed {0} in {1}ms".format(
                    func.__name__, time.time() - now
                )
            )
            return return_value
    
        return wrapper
    
    
    def test1(a, b, c):
        print("	test1 called")
    
    
    def test2(a, b):
        print("	test2 called")
    
    def test3(a, b):
        print("	test3 called")
        time.sleep(1)
    
    
    @log_calls
    def test4(a, b):
        print("	test4 called")
    
    
    test1 = log_calls(test1)
    test2 = log_calls(test2)
    test3 = log_calls(test3)
    
    test1(1, 2, 3)
    test2(4, b=5) # 测试 **kwargs
    test3(6, 7) #用 
    test4(6,b = 7) # @decorator synax
    

    The Decorator Pattern is also known as Wrapper.

    Advantage of Decorator Pattern:

    • It provides greater flexibility than static inheritance.

    • It enhances the extensibility of the object, because changes are made by coding new classes.

    • It simplifies the coding by allowing you to develop a series of functionality from targeted classes instead of coding all of the behavior into the object.

    用mokey-patching可以达到同样的效果

    来看下面这个实例:

    class A:
        def func(self):
            print("func() is being called")
    
    
    def monkey_f(self):
        print("monkey_f() is being called")
    
    
    if __name__ == "__main__":
        # replacing address of "func" with "monkey_f"
        A.func = monkey_f
        obj = A()
    
        # calling function "func" whose address got replaced
        # with function "monkey_f()"
        obj.func()
        # func() is being called
    

    Monkey patching is a technique to add, modify, or suppress the default behavior of a piece of code at runtime without changing its original source code.

    Reference

    https://www.javatpoint.com/decorator-pattern

  • 相关阅读:
    第一张图:每天初始化交易流程图
    Django部署服务时候报错:SQLite 3.8.3 or later is required (found 3.7.17)
    LOJ2494. 「AHOI / HNOI2018」寻宝游戏
    luoguP4429 [BJOI2018]染色
    LOJ2720. 「NOI2018」你的名字
    LOJ2262. 「CTSC2017」网络
    LOJ2398. 「JOISC 2017 Day 3」自然公园
    ULR1 B. 【ULR #1】光伏元件
    CF Good Bye 2020 题解&总结 A~G
    vue 导入.md文件(markdown转HTML)
  • 原文地址:https://www.cnblogs.com/buzhouke/p/14258651.html
Copyright © 2011-2022 走看看