You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python子类调用父类方法报错:AttributeError问题排查

问题解答:super调用父类方法报错的原因与修复

你的问题出在super()的参数使用错误:

  • 你写了super(Parent, self),但第一个参数应该传当前子类Child,而不是父类Parent。

原因分析

Python的super()函数是基于方法解析顺序(MRO)来查找下一个要调用的类。当你传入Parent作为第一个参数时,它会在self(也就是Child实例)的MRO链里找到Parent的下一个类——也就是object,而object类并没有定义is_valid方法,所以会抛出AttributeError: 'super' object has no attribute 'is_valid'。

修复后的代码

import abc
class Parent(abc.ABC):
 
   def is_valid(self, thing):
      return thing is not None

class Child(Parent):
   def is_valid(self, thing):
      # 写法1:传入当前子类Child
      return super(Child, self).is_valid(thing) and thing > 5
      # 写法2(Python3推荐):省略参数,自动识别当前类和self
      # return super().is_valid(thing) and thing > 5

a = Child()
print(a.is_valid(6))

补充说明

Python3中super()可以不用传任何参数,它会自动获取当前类(Child)和self对象,这种写法更简洁,也能避免参数传错的问题。

内容的提问来源于stack exchange,提问作者Stevie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 00:05:54