Python中的方法重载
时间:2020-01-09 10:44:19 来源:igfitidea点击:
在这篇文章中,我们将了解Python中的方法重载如何工作。
什么是方法重载
方法重载也是一种面向对象的编程概念,它指出在一个类中,我们可以具有两个或者更多个具有相同名称的方法,其中方法的类型或者传递的参数数量不同。
Python中的方法重载
方法重载在Python中是不支持的。在Python中,如果我们尝试重载方法,则不会出现任何编译时错误,而只会识别最后定义的方法。调用任何其他重载方法都会在运行时导致错误。
例如,以下是一个类定义,其中包含两个重载方法,一个带有2个参数,另一个带有3个参数。
class OverloadExample:
# sum method with two parameters
def sum(self, a, b):
s = a + b
print('Sum is:', s)
# overloaded sum method with three parameters
def sum(self, a, b, c):
s = a + b + c
print('Sum is:', s)
obj = OverloadExample()
obj.sum(1,2,3)
obj.sum(4, 5)
输出:
Sum is: 6
Traceback (most recent call last):
File "F:/theitroad/Python/Programs/Overload.py", line 15, in
obj.sum(4, 5)
TypeError: sum() missing 1 required positional argument: 'c'
如我们所见,带有3个参数的方法是最后一个,因此可以调用,但是调用具有两个参数的sum方法会导致错误。
如何在Python中实现方法重载
如果要用Python编写可以使用不同数量的参数的方法或者模拟方法重载,则可以在Python中使用默认参数或者可变长度参数。
1.使用默认参数
在此,将None关键字指定为默认值。
class OverloadExample:
# sum method with default as None for parameters
def sum(self, a=None, b=None, c=None):
# When three params are passed
if a is not None and b is not None and c is not None:
s = a + b + c
print('Sum is:', s)
# When two params are passed
elif a is not None and b is not None:
s = a + b
print('Sum is:', s)
obj = OverloadExample()
obj.sum(1, 2, 3)
obj.sum(4, 5)
输出:
Sum is: 6 Sum is: 9
2.使用变长参数
我们可以使用可变长度参数,该参数可以接受不同数量的值。
class OverloadExample:
def sum(self, *args):
s = 0
for num in args:
s += num
print('Sum is:', s)
obj = OverloadExample()
obj.sum(1, 2, 3)
obj.sum(4, 5)
输出:
Sum is: 6 Sum is: 9

