Python中方法重载和方法覆盖的区别
方法重载
方法重载是编译时多态性的一个例子。在这种情况下,同一类的多个方法共享具有不同签名的相同方法名称。方法重载用于为方法的行为添加更多内容,方法重载不需要多个类。
注意:Python 不支持方法重载。可以重载方法,但只能使用最新定义的方法。
例子:
# Function to take multiple arguments
def add(datatype, *args):
# if datatype is int
# initialize answer as 0
if datatype =='int':
answer = 0
# if datatype is str
# initialize answer as ''
if datatype =='str':
answer =''
# Traverse through the arguments
for x in args:
# This will do addition if the
# arguments are int. Or concatenation
# if the arguments are str
answer = answer + x
print(answer)
# Integer
add('int', 5, 6)
# String
add('str', 'Hi ', 'geekdocsGeeks')
运行结果如下:
11
Hi geekdocsGeeks
2. 方法覆盖
方法覆盖是运行时多态性的一个例子。其中,父类已经提供的方法的具体实现由子类提供。它用于更改现有方法的行为,并且需要至少两个类来覆盖方法。在方法覆盖中,总是需要继承,因为它是在父类(超类)和子类(子类)方法之间完成的。
python中方法覆盖的示例:
class A:
def fun1(self):
print('feature_1 of class A')
def fun2(self):
print('feature_2 of class A')
class B(A):
# Modified function that is
# already exist in class A
def fun1(self):
print('Modified feature_1 of class A by class B')
def fun3(self):
print('feature_3 of class B')
# Create instance
obj = B()
# Call the override function
obj.fun1()
运行结果:
Modified feature_1 of class A by class B
Python中方法重载和方法覆盖的区别:
编号 | 方法重载 | 方法重载 |
---|---|---|
1 | 在方法重载中,方法或函数必须具有相同的名称和不同的签名。 | 在方法覆盖中,方法或函数必须具有相同的名称和相同的签名。 |
2 | 方法重载是编译时多态的一个例子。 | 方法覆盖是运行时多态性的一个例子。 |
3 | 在方法重载中,可能需要也可能不需要继承。 | 在方法覆盖中,总是需要继承。 |
4 | 类内方法之间进行方法重载。 | 方法覆盖是在父类和子类方法之间完成的。 |
5 | 方法重载用于为方法的行为添加更多内容。 | 方法重载用于更改现有方法的行为。 |
6 | 在方法重载中,不需要一个以上的类。 | 在方法覆盖中,至少需要两个类。 |