Python中关于super()函数的疑问与用法解析

网上很多文档都说,super()返回的是 MRO 中的下一个类。

class Animal(object):
    def __init__(self, name):
        self.name = name
def greet(self):
    print('Hello, I am {}'.format(self.name))

class Dog(Animal): def greet(self): super().greet() print(‘WangWang…’)

dog = Dog(‘dog’) dog.greet()

按照网上的教程理解,super()返回的是 mro 中的下一个类,那么 super()返回的应该是 Animal,那么如果是 Animal 的话,super().greet(),就应该相当于Animal.greet(),但是这样的话肯定是不能调用的,应该是Animal.greet(self),才好理解。

而且通过 print(super()) 得到的返回值是 <super: <class 'Dog'>, <Dog object>>,说明 super 是一个类。

那么,super() 返回的到底是什么?


Python中关于super()函数的疑问与用法解析

2 回复

super()是Python面向对象编程中调用父类方法的关键机制。它的核心作用是在子类中调用父类的实现,特别是在多重继承场景下能按照MRO(方法解析顺序)正确工作。

基本用法:

class Parent:
    def __init__(self):
        print("Parent init")
        
class Child(Parent):
    def __init__(self):
        super().__init__()  # 调用Parent.__init__
        print("Child init")

多重继承中的MRO:

class A:
    def method(self):
        print("A")

class B(A):
    def method(self):
        super().method()
        print("B")

class C(A):
    def method(self):
        super().method()
        print("C")

class D(B, C):
    def method(self):
        super().method()
        print("D")

d = D()
d.method()
# 输出:A C B D(按MRO顺序执行)

关键点:

  1. super()返回的是代理对象,不是父类本身
  2. 在类方法中,super()会自动传递当前实例和类
  3. 可以显式指定类和实例:super(Child, self).__init__()
  4. 在多重继承中,super()遵循C3线性化算法确定的MRO顺序

常见误区:

  • super()不是直接调用"父类",而是调用MRO中的下一个类
  • 在静态方法中不能使用无参数的super()
  • Python 2和3的super()语法不同

实用技巧:

# 调用特定父类方法(不推荐,破坏继承结构)
class Child(Parent):
    def method(self):
        Parent.method(self)  # 直接调用,绕过super机制

一句话总结: super()是确保继承链正确工作的关键,理解MRO才能真正掌握它。


<br>super([type[, object-or-type]])<br>Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.<br>

https://docs.python.org/3/library/functions.html?highlight=super#super

回到顶部