【代码技巧】python用装饰器监听函数输入输出,以及在类内启用禁用

1. 装饰器监听函数输入输出

def monitor(func):
    def wrapper(*args, **kwargs):
        print(f"Function {func.__name__} called with args: {args}, kwargs: {kwargs}")
        result = func(*args, **kwargs)
        print(f"Function {func.__name__} returned: {result}")
        return result
    return wrapper

# 使用装饰器监听函数的输入和输出
@monitor
def add(a, b):
    return a + b

result = add(3, 5)
# 输出:
# Function add called with args: (3, 5), kwargs: {}
# Function add returned: 8

 

 

 

2. 类内启用禁用:

def monitor(func):
    def wrapper(self, *args, **kwargs):
        if self.monitor_enabled:
            print(f"Function {func.__name__} called with args: {args}, kwargs: {kwargs}")
        result = func(self, *args, **kwargs)
        if self.monitor_enabled:
            print(f"Function {func.__name__} returned: {result}")
        return result
    return wrapper

class MyClass:
    def __init__(self):
        self.monitor_enabled = True

    def enable_monitor(self):
        self.monitor_enabled = True

    def disable_monitor(self):
        self.monitor_enabled = False

    @monitor
    def my_method(self, arg):
        print("Inside my_method")
        return arg * 2

测试输出:

obj = MyClass()
obj.my_method(3)  # 使用监听
obj.disable_monitor()  # 禁用监听
obj.my_method(4)  # 不使用监听
obj.enable_monitor()  # 启用监听
obj.my_method(5)  # 使用监听

>>>Function my_method called with args: (3,), kwargs: {}
>>>Inside my_method
>>>Function my_method returned: 6
>>>Inside my_method
>>>Function my_method called with args: (5,), kwargs: {}
>>>Inside my_method
>>>Function my_method returned: 10
  1. 在运行的时候脚本内部赋一个装饰器
    https://stackoverflow.com/questions/2237624/applying-a-decorator-to-every-method-in-a-class
for name, obj in getmembers(TestCase, ismethod):
   if name.startswith("test_"):
       setattr(TestCase, name, login_testuser(obj))
posted @ 2024-03-27 01:53  Zer0_Chambers  阅读(9)  评论(0编辑  收藏  举报