When dealing with polymorphic objects, just pay attention to its interface, Python does not need to display the writing (like Java) interface, in the use of objects first assumed that the interface, if not actually included, in the run error.
The code is 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
The code is as follows:
FA = gunfactory (handgun)
Gun = Fa.produce ()
/* As long as the gun, it is believed that it has the function of firing, if there is no fire function, the program operation in the error * * *
Gun.fire ()
As you can see, Python is not at the language level to ensure the correctness of the interface, but only with the documentation and code (you can check the presence of the interface in the code, HASATTR (Gun, ' fire '), compared to the normal static language.