Python 面向对象中 super 的作用?

在 Python 的面向对象编程中,我们经常会用到 super() 这个函数。那么,super() 到底有什么作用呢?

super() 函数的作用是调用父类中的方法。在 Python 中,一个类可以继承自另一个类,这个被继承的类称为父类,继承自父类的类称为子类。当一个子类继承了父类的方法时,如果想要在子类中使用父类的方法,就可以使用 super() 函数。

举个例子,假设我们有一个父类 Animal 和一个子类 Dog,其中 Animal 有一个 eat() 方法:

class Animal:
    def eat(self):
        print("Animal is eating")

class Dog(Animal):
    def eat(self):
        print("Dog is eating")

在上面的代码中,Dog 继承自 Animal,同时重写了 eat() 方法。如果我们想在 Dog 中调用父类 Animal 的 eat() 方法,就可以使用 super():

class Dog(Animal):
    def eat(self):
        super().eat()
        print("Dog is eating")

在上面的代码中,super().eat() 调用了父类 Animal 的 eat() 方法,然后再执行子类 Dog 的 eat() 方法。

需要注意的是,super() 函数只能用于新式类中。在 Python 2.x 中,有经典类和新式类之分,而在 Python 3.x 中,只有新式类。如果要在 Python 2.x 中使用 super(),需要将类定义为新式类:

class Animal(object):
    def eat(self):
        print("Animal is eating")

class Dog(Animal):
    def eat(self):
        super(Dog, self).eat()
        print("Dog is eating")

在上面的代码中,Animal 类继承自 object,这样就定义成了新式类,可以使用 super() 函数。

此外,当一个类继承自多个父类时,super() 函数的调用顺序也很重要。在 Python 中,多重继承的顺序是从左到右,即先继承的父类中的方法会优先被调用。因此,在使用 super() 函数时,应该考虑好调用顺序,以免出现错误。

总之,super() 函数是 Python 面向对象编程中非常重要的一个函数,可以帮助我们更方便地调用父类的方法。在使用时,需要注意类的继承关系和调用顺序,以免出现错误。