一、重载(overload):
定义:
同一个类中的函数具有相同名称,但参数列表不同(参数个数,参数类型),这样同名不同参数的函数之间,互为重载函数,属于编译时多态。
特点:
①同一个类中(相同作用域)
②函数名称必须相同
③函数参数必须不同
④函数返回类型可同可不同,不重要
二、重写(override)
也称为覆盖,是指子类重新定义父类中有相同函数名,参数列表,返回类型的虚函数。子类对象使用这个方法时,将调用子类中的定义,父类中的定义如同被“屏蔽”了,属于运行时多态。
特点:
①函数名、参数列表、返回类型必须完全与被重写方法的相同;
②访问权限不能比父类中被重写的方法的访问权限更低
③重写函数和被重写函数都是virtual函数(派生类函数可以不带virtual关键字)
④声明为final的方法不能被重写。
⑤声明为static的方法不能被重写,但是能够被再次声明。
⑥构造函数不能被重写
三、Difference between Method Overloading and Method Overriding in Python
1. Overload
Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.
Note: Python does not support method overloading. We may overload the methods but can only use the latest defined method.
Example:
# 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 ', 'Geeks')
2. Override
Method Overriding:
Method overriding is an example of run time polymorphism. In this, the specific implementation of the method that is already provided by the parent class is provided by the child class. It is used to change the behavior of existing methods and there is a need for at least two classes for method overriding. In method overriding, inheritance always required as it is done between parent class(superclass) and child class(child class) methods.
Example of Method Overriding in 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()