Python polymorphic sample code from the python learning manual

  • 2020-04-02 13:22:15
  • OfStack

When dealing with a polymorphic object, you only need to focus on its interface. In python, you don't need to write the interface shown (like Java).


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()

The client


fa = gunFactory(handGun)
gun = fa.produce()

gun.fire()

As you can see, python does not guarantee the correctness of the interface at the language level, compared to the general static language. It relies on documentation, code (you can check the existence of the interface in the code,hasattr(gun,'fire')).


Related articles: