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

Python中使用super()函数如何指定调用特定父类的同名方法

问题背景

在Python多继承场景下,你需要在子类child的identify2方法中,通过super()关键字指定调用第二个父类Parent2的同名identify方法。默认无参的super()调用会按照方法解析顺序(MRO)优先调用继承顺序里排在前面的Parent1的identify方法,无法达到预期。

解决方案

修改identify2方法的super()调用逻辑,给super()传入两个参数:第一个参数指定MRO查找的起始前置类Parent1,第二个参数传入实例对象self,就会从Parent1的下一个类(即Parent2)开始查找目标方法,同时需要补充return返回方法调用结果,否则会返回None。
修改后的完整代码如下:

class Parent1:
  def identify(self):
    return "This method is called from Parent1"
    
class Parent2:
  def identify(self):
    return "This method is called from Parent2"
    
# declare child class here
class child(Parent1, Parent2):
  def identify(self):
    return "This method is called from Child"
  def identify2(self):
    # 指定从Parent1的下一个类开始查找对应方法
    return super(Parent1, self).identify()
  

child_object = child()
# 预期输出:
print( child_object.identify() )        # This method is called from Child
print( child_object.identify2() )       # This method is called from Parent2

原理解释

  • Python多继承的类会生成固定的方法解析顺序(MRO)列表,当前场景可以通过child.__mro__查看MRO顺序为:(<class '__main__.child'>, <class '__main__.Parent1'>, <class '__main__.Parent2'>, <class 'object'>)
  • super(type, obj)的作用是:在obj所属类的MRO列表中,找到type之后的第一个类,调用对应方法。这里传入Parent1作为第一个参数,就会跳过Parent1,直接匹配后续Parent2的identify方法,完全符合必须使用super()关键字的要求。

内容的提问来源于stack exchange,提问作者Renzm.6958

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:24:04