python 函数继承
时间: 2023-10-19 13:30:47 浏览: 43
Python中的函数继承是指一个子类可以继承父类中的函数定义。这样子类就可以使用父类中定义的函数,而不需要重新编写相同的代码。
要实现函数继承,可以在子类中使用特殊的关键字`super()`来调用父类中的函数。通过这样的调用,子类可以重用父类的函数,同时还可以在子类中添加自己的特定实现。
下面是一个简单的示例:
```python
class ParentClass:
def func(self):
print("This is a function from the parent class.")
class ChildClass(ParentClass):
def func(self):
super().func() # 调用父类的函数
print("This is an additional function from the child class.")
# 创建子类对象
obj = ChildClass()
# 调用子类对象的函数
obj.func()
```
输出:
```
This is a function from the parent class.
This is an additional function from the child class.
```
在上述示例中,`ChildClass`继承了`ParentClass`。子类中的`func`方法使用`super().func()`调用了父类中的`func`方法,并在其后添加了自己的实现。
这样,通过函数继承,我们可以在子类中重用父类的功能,并且还可以进行扩展和定制化。