Python2.7装饰器类继承场景下super调用报错问题求助
解决Python2.7中装饰器类使用super报错的问题
问题根源
Python2.7里super()仅支持新式类(继承自object的类),且参数必须严格匹配当前类和实例。如果你的装饰器类是旧式类(未继承object),或者super的第一个参数不是正确的类类型,就会触发TypeError: super: argument 1 must be type。
具体解决思路
强制装饰器类为新式类
Python2.7中,所有要使用super的类必须显式继承object,否则属于旧式类,不支持super语法。修改类定义:# 错误写法(旧式类) class together: def __init__(self, func): super(together, self).__init__() self.func = func # 正确写法(新式类) class together(object): def __init__(self, func): super(together, self).__init__() self.func = func校验super参数的正确性
确保super的第一个参数是当前类的准确名称(拼写完全一致),第二个参数是self。比如在together类的__init__方法中,必须写super(together, self).__init__(),不能写错类名或传入其他对象。替代方案:直接调用父类构造方法
如果不想纠结super的参数问题,可以直接调用父类(object)的__init__方法,效果完全一致:class together(object): def __init__(self, func): object.__init__(self) # 替代super调用 self.func = func
完整兼容示例代码(Python2.7)
class LogDecorator(object): def __init__(self, func): super(LogDecorator, self).__init__() self.func = func def __call__(self, *args, **kwargs): print("[LOG] 函数执行前") result = self.func(*args, **kwargs) print("[LOG] 函数执行后") return result @LogDecorator def say_hello(name): print("Hello %s" % name) # Python2.7不支持f-string,需用格式化字符串 say_hello("Alice")
内容的提问来源于stack exchange,提问作者Kaushik Shah
相关产品推荐
相关产品推荐

