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

  • 相关阅读:
    网络教程(2)光纤和RF编码简介
    网络教程(1)通过导线传播数字信号
    C语言基础 (11) 结构体 ,共用体 枚举 typedef
    C语言基础 (10) 变量作用域,生命周期 内存结构
    C语言基础 (9) 数组指针
    C语言基础 (8) 常用字符串处理函数
    C语言基础 (7) 输入输出
    短视频图像处理 OpenGL ES 实践
    短视频 SDK 6大功能技术实现方式详解
    从 HTTP 到 HTTPS 再到 HSTS
  • 原文地址:https://www.cnblogs.com/buzhouke/p/14258651.html
Copyright © 2011-2022 走看看