面试题答案
一键面试在Python类继承中,有两种常见方式在子类方法中调用父类被重写的方法:
- 使用
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()
- 通过父类名调用:
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
参数。这两种方式都能实现在子类方法中调用父类被重写的方法。