MST

星途 面试题库

面试题:Python中继承类的方法重写规则

在Python中,当子类继承父类并对父类的方法进行重写时,有哪些需要注意的规则?请举例说明如何正确重写方法,并且阐述重写方法中如何调用父类被重写的方法。
29.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

子类重写父类方法的注意规则

  1. 方法签名需一致:子类重写的方法与父类被重写的方法,其方法名、参数列表(包括参数个数、参数顺序、参数默认值等)应保持一致。否则,Python会将其视为一个新的方法,而非重写。
  2. 访问权限:虽然Python没有像Java等语言那样严格的访问权限修饰符,但如果父类方法有一定的访问约定(如以单下划线开头表示内部使用,不建议外部直接调用),子类重写时也应遵循类似约定。

正确重写方法示例

class Animal:
    def speak(self):
        print("Animal makes a sound")


class Dog(Animal):
    def speak(self):
        print("Dog barks")


dog = Dog()
dog.speak()

在上述代码中,Dog类继承自Animal类,并对speak方法进行了重写。当调用dog.speak()时,会执行Dog类中重写后的speak方法,输出Dog barks

重写方法中调用父类被重写的方法

  1. 使用super()函数:在Python 3中,推荐使用super()函数来调用父类的方法。
class Animal:
    def speak(self):
        print("Animal makes a sound")


class Dog(Animal):
    def speak(self):
        super().speak()
        print("Dog barks")


dog = Dog()
dog.speak()

这里,super().speak()调用了父类Animalspeak方法,然后再执行子类Dogspeak方法的其他逻辑,输出结果为:

Animal makes a sound
Dog barks
  1. 直接调用父类方法(Python 2风格,Python 3也可用但不推荐):通过类名直接调用父类方法,并显式传入self参数。
class Animal:
    def speak(self):
        print("Animal makes a sound")


class Dog(Animal):
    def speak(self):
        Animal.speak(self)
        print("Dog barks")


dog = Dog()
dog.speak()

同样,这种方式也能达到调用父类被重写方法的目的,但super()函数在处理多重继承等复杂情况时更为灵活和高效。