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.
Copy Code code as follows:
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
Copy Code code as follows:
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 in operation of the error * *
Gun.fire ()
You can see that Python does not have the language level to guarantee the correctness of the interface, as opposed to the normal static language, and can only rely on documents, code to ensure that the interface exists in the code, HASATTR (Gun, ' fire '))