Python 中支持函数继承的方法一般有两种:
- 子函数调用父函数
- 装饰器
子函数调用父函数
子函数调用父函数的方法,即在子函数中使用 super()
函数去调用父函数的同名方法。这个方法主要适用于类之间的方法继承。
示例代码:
class Parent:
def foo(self):
print("This is parent function")
class Child(Parent):
def foo(self):
super().foo()
print("This is child function")
c = Child()
c.foo()
上述代码中,我们定义了一个父类 Parent
和一个子类 Child
, Child
类继承了 Parent
类的方法,其中,子函数中使用 super()
函数去调用了父函数 foo()
,从而实现了子类继承父类方法的目的。
执行结果:
This is parent function
This is child function
装饰器
装饰器也是实现函数继承的一种方法。我们可以定义一个装饰器来扩展原函数(即父函数)的功能,从而实现子类继承父类方法的目的。
示例代码:
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
@log
def parent_function():
print("This is parent function")
@log
def child_function():
print("This is child function")
parent_function()
child_function()
上述代码中,我们定义了一个名为 log
的装饰器,这个装饰器会在原函数的基础上添加一行输出日志的代码,从而扩展了原函数的功能。
在使用装饰器时,只需在函数定义前添加 @log
即可调用装饰器,从而实现子函数继承父函数的目的。
执行结果:
call parent_function():
This is parent function
call child_function():
This is child function
注意:装饰器方法适用于函数之间的方法调用,不适用于类之间的方法继承。
总体而言,Python 中的函数继承方法还有很多种,上述只是其中的两种。我们可以选择不同的方法来满足不同的需求。