请使用装饰器为一个类的所有方法添加日志记录功能,记录方法的调用信息(如方法名、参数和返回值)。
# 定义一个装饰器函数,用于为类的方法添加日志记录功能
def log_method_calls(cls):
# 遍历类的所有方法
for name, method in cls.__dict__.items():
if callable(method):
# 定义一个包装函数,用于记录方法的调用信息
def wrapper(*args, **kwargs):
# 记录方法名和参数
print(f"调用方法: {name}, 参数: args={args}, kwargs={kwargs}")
# 调用原始方法并获取返回值
result = method(*args, **kwargs)
# 记录返回值
print(f"方法 {name} 的返回值为: {result}")
return result
# 将包装函数替换原始方法
setattr(cls, name, wrapper)
return cls
# 使用装饰器修饰一个类
@log_method_calls
class ExampleClass:
def greet(self, name):
return f"Hello, {name}!"
def add(self, a, b):
return a + b
# 测试类的功能
if __name__ == "__main__":
example = ExampleClass()
print(example.greet("World"))
print(example.add(2, 3))
示例解析
- 装饰器定义:
log_method_calls是一个类装饰器,它会遍历类的所有方法,并为每个方法添加日志记录功能。 - 包装函数:
wrapper函数会在方法调用前后打印日志信息,包括方法名、参数和返回值。 - 替换方法:使用
setattr将包装函数替换类中的原始方法。 - 类修饰:通过
@log_method_calls语法将装饰器应用到ExampleClass上。 - 测试运行:调用类的方法时,会自动打印日志信息,例如:
- 调用
greet方法时输出:调用方法: greet, 参数: args=(<__main__.ExampleClass object at 0x7f8a1c1a5d30>, 'World'), kwargs={} 方法 greet 的返回值为: Hello, World! - 调用
add方法时输出:调用方法: add, 参数: args=(<__main__.ExampleClass object at 0x7f8a1c1a5d30>, 2, 3), kwargs={} 方法 add 的返回值为: 5
- 调用
进一步优化
如果需要更精细的控制(例如只记录某些方法的日志),可以改进装饰器以支持选择性记录。例如:
def log_method_calls(*methods_to_log):
def decorator(cls):
# 遍历类的所有方法
for name, method in cls.__dict__.items():
if callable(method) and (not methods_to_log or name in methods_to_log):
def wrapper(*args, **kwargs):
print(f"调用方法: {name}, 参数: args={args}, kwargs={kwargs}")
result = method(*args, **kwargs)
print(f"方法 {name} 的返回值为: {result}")
return result
setattr(cls, name, wrapper)
return cls
return decorator
# 只记录 add 方法的日志
@log_method_calls('add')
class ExampleClass:
def greet(self, name):
return f"Hello, {name}!"
def add(self, a, b):
return a + b
这种方法可以灵活地控制日志记录的粒度,适用于实际开发中的复杂需求。