📜  Python方法重载和方法覆盖的区别

📅  最后修改于: 2021-09-11 04:42:08             🧑  作者: Mango

方法重载:
方法重载是编译时多态的一个例子。在这种情况下,同一类的多个方法共享具有不同签名的相同方法名称。方法重载用于为方法的行为添加更多内容,并且方法重载不需要一个以上的类。
注意: Python不支持方法重载。我们可以重载方法,但只能使用最新定义的方法。
例子:

Python3
# 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')


Python3
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()


输出:

11
Hi Geeks

方法覆盖:
方法覆盖是运行时多态的一个例子。其中,父类已经提供的方法的具体实现由子类提供。它用于更改现有方法的行为,并且至少需要两个类来覆盖方法。在方法覆盖中,继承总是需要的,因为它是在父类(超类)和子类(子类)方法之间完成的。
Python中方法覆盖的例子:

蟒蛇3

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方法重载和方法覆盖的区别:

S.NO Method Overloading Method Overriding
1. In the method overloading, methods or functions must have the same name and different signatures. Whereas in the method overriding, methods or functions must have the same name and same signatures.
2. Method overloading is a example of compile time polymorphism. Whereas method overriding is a example of run time polymorphism.
3. In the method overloading, inheritance may or may not be required. Whereas in method overriding, inheritance always required.
4. Method overloading is performed between methods within the class. Whereas method overriding is done between parent class and child class methods.
5. It is used in order to add more to the behavior of methods. Whereas it is used in order to change the behavior of exist methods.
6. In method overloading, there is no need of more than one class. Whereas in method overriding, there is need of at least of two classes.