Python Logger类装饰器添加参数后报TypeError问题求助
问题分析
报错的核心原因是:带参数的装饰器需要返回一个装饰器函数,而你当前的catch函数直接把func作为第一个参数,当调用Logger.catch(file_path='xxx')时,Python会执行这个调用,但此时没有传入func,因此触发TypeError。
解决方案
修改Logger.catch为三层嵌套结构,让它先接收file_path参数,再返回真正的装饰器(接收func的函数)。同时,因为catch是类中的方法,需要用@staticmethod标记,避免Python自动传入self参数。
修改后的完整代码:
import sys import traceback class Logger(): @staticmethod def catch(file_path=None): # 外层函数接收file_path参数,返回装饰器 def decorator(func): # 装饰器接收目标函数func def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: _, _, tb = sys.exc_info() traceback_info = traceback.extract_tb(tb) line = traceback_info[-1][1] file = traceback_info[-1][0] function_name = traceback_info[-1][2] Logger.error(log_msg=str(e), highlighting=True, print_out=True, line=[line, file, function_name], file_path=file_path) return wrapper return decorator # 补充error方法的示例实现(假设你已有实现可替换) @staticmethod def error(log_msg, highlighting=True, print_out=True, line=None, file_path=None): log_content = f"Error in {line[2]} (file: {line[0]}, line: {line[1]}): {log_msg}" if print_out: print(log_content) if file_path: with open(file_path, 'a', encoding='utf-8') as f: f.write(log_content + '\n')
验证使用
你的示例代码可以正常运行:
@Logger.catch(file_path='tests/example.log') def example_function(): """ Not working function, because of division by zero """ var1 = 5 var = 0 result = var1 / var print(result) example_function()
运行后,控制台会打印错误信息,同时tests/example.log文件也会写入对应的日志内容。
关键改动说明
- 新增
decorator函数:作为真正的装饰器接收func,解决参数传递顺序问题 - 添加
@staticmethod:确保调用Logger.catch()时不会自动传入类实例/类本身的参数 - 三层嵌套结构:适配带参数装饰器的执行逻辑:
Logger.catch(file_path=...)→ 返回decorator→decorator(func)→ 返回wrapper
内容的提问来源于stack exchange,提问作者zlElo
相关产品推荐
相关产品推荐

