Class factory in Python

后端 未结 7 2364
半阙折子戏
半阙折子戏 2020-11-28 18:37

I\'m new to Python and need some advice implementing the scenario below.

I have two classes for managing domains at two different registrars. Both have the same inte

7条回答
  •  天涯浪人
    2020-11-28 19:02

    In Python you can change the actual class directly:

    class Domain(object):
      def __init__(self, domain):
        self.domain = domain
        if ...:
          self.__class__ = RegistrarA
        else:
          self.__class__ = RegistrarB
    

    And then following will work.

    com = Domain('test.com') #load RegistrarA
    com.lookup()
    

    I'm using this approach successfully.

提交回复
热议问题