Class factory in Python

后端 未结 7 2321
半阙折子戏
半阙折子戏 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条回答
  • You can create a 'wrapper' class and overload its __new__() method to return instances of the specialized sub-classes, e.g.:

    class Registrar(object):
        def __new__(self, domain):
            if ...:
                return RegistrarA(domain)
            elif ...:
                return RegistrarB(domain)
            else:
                raise Exception()
    

    Additionally, in order to deal with non-mutually exclusive conditions, an issue that was raised in other answers, the first question to ask yourself is whether you want the wrapper class, which plays the role of a dispatcher, to govern the conditions, or it will delegate it to the specialized classes. I can suggest a shared mechanism, where the specialized classes define their own conditions, but the wrapper does the validation, like this (provided that each specialized class exposes a class method that verifies whether it is a registrar for a particular domain, is_registrar_for(...) as suggested in other answers):

    class Registrar(object):
        registrars = [RegistrarA, RegistrarB]
        def __new__(self, domain):
            matched_registrars = [r for r in self.registrars if r.is_registrar_for(domain)]
    
            if len(matched_registrars) > 1:
                raise Exception('More than one registrar matched!')
            elif len(matched_registrars) < 1:
                raise Exception('No registrar was matched!')
            else:
                return matched_registrars[0](domain)
    
    0 讨论(0)
提交回复
热议问题