Polymorphism is a basic feature of object-oriented language, and polymorphism means that variables do not know what the referenced object is, and behave differently depending on the object of reference. When dealing with polymorphic objects, you only need to focus on its interface, Python does not need to display the written (like Java) interface, in the use of objects to assume the use of the interface, if not actually included, in the run error.
Class handgun ():
def __init__ (self):
Pass
def fire (self):
print ' Handgun fire '
Class Carbine ():
def __init__ (self):
Pass
def fire (self):
print ' Carbine fire '
Import handgun
Import Carbine
Class Gunfactory ():
def __init__ (Self,gun_type):
Self.gun_type = Gun_type
def produce (self):
if handgun = = Self.gun_type:
Return Handgun.handgun ()
Else
Return Carbine.carbine ()
Client
FA = gunfactory (handgun)
Gun = Fa.produce ()
As long as it is a gun, it is considered to have the function of firing, if there is no fire function, the program will be running error
Gun.fire ()
You can see that Python does not have the language level to guarantee the correctness of the interface, and can only rely on documents, code to ensure that the interface exists hasattr (gun, ' Fire ') in code.
Let's look at one more example, the method polymorphism:
Let's start by creating a file named Myclass.py, with the following code
__author__= ' Mxi4oyu '
Classpeople:
Def say (self):
Print ("Hello everyone!") ")
Classstudent:
Def say (self):
Print ("Good teacher!") ")
We'll create a main.py file with the following code:
__author__= ' Mxi4oyu '
Fromrandom Import Choice
Importmyclass
P1=myclass.people ()
Stu1=myclass.student ()
#通过choice方法我们可以随机选择列表中的某一项
Obj=choice ([P1,STU1])
Print (the type (obj))
Obj.say ()
The temporary object obj we created is taken from a random function and we don't know its exact type, but we can do the same thing with it. That is, let it call the Say method, and then, depending on its type, behaves differently. This is polymorphism.