Class factory in Python

后端 未结 7 2347
半阙折子戏
半阙折子戏 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:06

    Here a metaclass implicitly collects Registars Classes in an ENTITIES dict

    class DomainMeta(type):
        ENTITIES = {}
    
        def __new__(cls, name, bases, attrs):
            cls = type.__new__(cls, name, bases, attrs)
            try:
                entity = attrs['domain']
                cls.ENTITIES[entity] = cls
            except KeyError:
                pass
            return cls
    
    class Domain(metaclass=DomainMeta):
        @classmethod
        def factory(cls, domain):
            return DomainMeta.ENTITIES[domain]()
    
    class RegistrarA(Domain):
        domain = 'test.com'
        def lookup(self):
            return 'Custom command for .com TLD'
    
    class RegistrarB(Domain):
        domain = 'test.biz'
        def lookup(self):
            return 'Custom command for .biz TLD'
    
    
    com = Domain.factory('test.com')
    type(com)       # 
    com.lookup()    # 'Custom command for .com TLD'
    
    com = Domain.factory('test.biz')
    type(com)       # 
    com.lookup()    # 'Custom command for .biz TLD'
    

提交回复
热议问题