What is polymorphism? What is the mechanism for implementing polymorphism? 【Lebo TestPro】

The so-called polymorphism: the type at the time of definition is different from the type at runtime, and it becomes polymorphism at this time. The concept of polymorphism is applied to strongly typed languages ​​such as Java and C#, while Python advocates "duck typing".

Duck Type: Although I wanted a "duck", you gave me a bird. But as long as the bird walks like a duck, quacks like a duck, and swims like a duck, I consider it a duck.

Python's polymorphism is to weaken the type. The focus is on whether the object parameters have specified attributes and methods. If so, it is considered appropriate, regardless of whether the type of the object is correct.
 Python pseudocode to implement polymorphism in Java or C#

class F1(object):
    def show(self):
        print('F1.show')
class S1(F1):
    def show(self):
        print('S1.show')
class S2(F1):
    def show(self):
        print('S2.show')
#由于在Java或C#中定义函数参数时,必须指定参数的类型# 为了让Func函数既可以执行S1对象的show方法,又可以执行S2对象的show方法,# 所以在def Func的形参中obj的类型是 S1和S2的父类即F1# # 而实际传入的参数是:S1对象和S2对象
def Func(F1 obj): 
    """Func函数需要接收一个F1类型或者F1子类的类型"""

    print(obj.show())

s1_obj = S1()
Func(s1_obj) # 在Func函数中传入S1类的对象 s1_obj,执行 S1 的show方法,结果:S1.show

s2_obj = S2()
Func(s2_obj) # 在Func函数中传入Ss类的对象 ss_obj,执行 Ss 的show方法,结果:S2.show

Popular point of understanding: defining the variable obj means that the type is: the type of F1, but when the Func function is actually called, it is not necessarily an instance object of the F1 class, but may be an instance object of its subclass
. case is called polymorphism

 Python "duck typing"

class F1(object):
    def show(self):
        print('F1.show')
class S1(F1):
    def show(self):
        print('S1.show')
class S2(F1):
    def show(self):
        print('S2.show')
def Func(obj):  
    # python是弱类型,即无论传递过来的是什么,obj变量都能够指向它,这也就没有所谓的多态了(弱化了这个概念)
    print(obj.show())

s1_obj = S1()
Func(s1_obj) 

s2_obj = S2()
Func(s2_obj)

For more information, please send a private message~
insert image description here

Guess you like

Origin blog.csdn.net/leboxy/article/details/110484024