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("\ttest1 called")


def test2(a, b):
    print("\ttest2 called")

def test3(a, b):
    print("\ttest3 called")
    time.sleep(1)


@log_calls
def test4(a, b):
    print("\ttest4 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

posted @ 2021-01-10 16:19  不周客  阅读(78)  评论(0编辑  收藏  举报