使用functools.singledispatchmethod装饰器报错IndexError:元组索引越界
使用functools.singledispatchmethod时的问题分析
问题根源
你调用obj.m()时未传入任何参数,而singledispatchmethod依赖第一个非self参数的类型来分发方法,此时没有参数可提取,导致代码尝试访问args[0]时触发IndexError: tuple index out of range。
另外,你的根方法m定义了必填参数iobj:object,调用时不传参本身就不符合方法签名要求。
修复方案
方案1:调用时传入对应类型的参数
按照方法定义传入参数,让singledispatchmethod能正常匹配类型:
obj.m("test") # 输出: string obj.m([1,2,3]) # 输出: list obj.m(123) # 输出: root
方案2:支持无参数调用
给根方法的参数设置默认值,并处理无参场景:
import functools class K: @functools.singledispatchmethod def m(self, iobj: object = None): if iobj is None: print("无参数传入") else: print("root") @m.register def m_from_str(self, istr: str): print('string') @m.register def m_from_object(self, ilist: list): print('list') obj = K() obj.m() # 输出: 无参数传入 obj.m("hello") # 输出: string
内容的提问来源于stack exchange,提问作者Toothpick Anemone
相关产品推荐
相关产品推荐

