Polymorphism is a basic feature of Object-Oriented Language. polymorphism means that variables do not know what the referenced object is, and different behavior methods are presented based on different referenced objects, the following uses an example to learn how to use it. when dealing with multi-state objects, you only need to pay attention to its interface. in python, you do not need to compile (like Java) interfaces, when using an object, assume that this interface exists. if it is not included, an error is returned during running.
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 it is a gun, it is considered to have the function of opening fire. if there is no function of opening fire, an error will be reported when the program is running */
Gun. fire ()
It can be seen that, compared with the general static language, python does not guarantee the correctness of the interface at the language level. it can only be ensured by documents and code (you can check whether the interface exists in the code, hasattr (gun, 'fire '))