重载==overload,重写==覆盖==override

12 篇文章 1 订阅

一、重载(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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值