MST

星途 面试题库

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

在Python类继承中,当子类重写父类方法时,如何在子类方法中调用父类被重写的方法?请举例说明。
31.2万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

在Python类继承中,有两种常见方式在子类方法中调用父类被重写的方法:

  1. 使用super()函数
class Parent:
    def my_method(self):
        print("这是父类的my_method方法")

class Child(Parent):
    def my_method(self):
        super().my_method()
        print("这是子类重写后的my_method方法")

child = Child()
child.my_method()
  1. 通过父类名调用
class Parent:
    def my_method(self):
        print("这是父类的my_method方法")

class Child(Parent):
    def my_method(self):
        Parent.my_method(self)
        print("这是子类重写后的my_method方法")

child = Child()
child.my_method()

在上述代码中,第一种方式使用super()函数,它会自动查找父类并调用相应方法;第二种方式直接通过父类名调用,需要手动传入self参数。这两种方式都能实现在子类方法中调用父类被重写的方法。