When processing a multi-state object, you only need to pay attention to its interface. In python, you do not need to compile (like Java) interfaces. This interface is assumed to exist before using objects, if not, an error is reported during running.
Copy codeThe 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
Copy codeThe 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 '))