在同一个类中使用装饰器

class MyClass:
    def __init__(self, name, value):
        self.name = name
        self.value = value

    @staticmethod
    def my_decorator(param1, param2):
        def decorator(func):
            def wrapper(self, *args, **kwargs):
                print(f"装饰器参数: param1={param1}, param2={param2}")
                print(f"访问实例属性: name={self.name}, value={self.value}")
                result = func(self, *args, **kwargs)
                return result

            return wrapper

        return decorator

    @my_decorator(param1="hello", param2="world")
    def greet(self):
        print("执行 greet 方法")


if __name__ == '__main__':
    obj1 = MyClass(111, 222)
    obj1.greet()

在一个类中使用另一个类中的装饰器

class DecoratorClass:
    def __init__(self):
        self.value = 0

    def helper_method(self, msg):
        self.value += 1
        print(f"self.value: {self.value}")
        print(f"helper_method called with message: {msg}")
        return f"processed {msg}"

    def decorator_with_params(self, param1, param2):
        def decorator(func):
            def wrapper(*args, **kwargs):
                # 调用类中的其他方法
                helper_result = self.helper_method(param2)
                print(f"decorator_with_params: {param1}, {param2}")
                print(f"helper_result: {helper_result}")
                # 执行原函数
                return func(*args, **kwargs)

            return wrapper

        return decorator


class UsageClass:
    def __init__(self):
        self.decorator_obj = DecoratorClass()

    @DecoratorClass().decorator_with_params("Hello", "world")
    def target_method(self, x):
        print(f"target_method called with x={x}")
        return x + 10


# 使用示例
if __name__ == "__main__":
    usage_obj = UsageClass()
    result = usage_obj.target_method(3)
    print(f"result: {result}")