子类和父类有相同的函数怎么判断什么时候调用子类的
时间: 2024-04-11 21:28:00 浏览: 17
当子类和父类有相同的函数时,可以使用方法重写(method overriding)来实现调用子类的函数。在子类中重新定义与父类相同名称的函数,并且通过关键字 `super` 调用父类的函数,可以实现在适当的时候调用子类的函数。以下是一个示例代码:
```python
class ParentClass:
def common_function(self):
print("This is the common function in the parent class.")
class ChildClass(ParentClass):
def common_function(self):
print("This is the common function in the child class.")
# 创建子类对象
child = ChildClass()
# 调用子类的函数
child.common_function()
# 使用 super 调用父类的函数
super(ChildClass, child).common_function()
```
输出结果:
```
This is the common function in the child class.
This is the common function in the parent class.
```
在上述示例中,`ChildClass` 继承自 `ParentClass`,且重写了 `common_function` 函数。通过 `super(ChildClass, child).common_function()` 可以调用父类的函数,从而实现了在需要的时候调用子类的函数。