Python中的类工厂 [英] Class factory in Python

查看:85
本文介绍了Python中的类工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,需要一些建议来实施以下方案.

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 interface, e.g.

class RegistrarA(Object):
    def __init__(self, domain):
        self.domain = domain

    def lookup(self):
        ...

    def register(self, info):
        ...

class RegistrarB(object):
    def __init__(self, domain):
        self.domain = domain

    def lookup(self):
        ...

    def register(self, info):
        ...

我想创建一个Domain类,给定域名,该类基于扩展名加载正确的注册商类,例如

I would like to create a Domain class that, given a domain name, loads the correct registrar class based on the extension, e.g.

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

biz = Domain('test.biz') #load RegistrarB
biz.lookup()

我知道这可以使用工厂函数来实现(请参见下文),但这是最好的方法还是使用OOP功能有更好的方法?

I know this can be accomplished using a factory function (see below), but is this the best way of doing it or is there a better way using OOP features?

def factory(domain):
  if ...:
    return RegistrarA(domain)
  else:
    return RegistrarB(domain)

推荐答案

我认为使用函数很好.

更有趣的问题是您如何确定要加载哪个注册服务商?一种选择是拥有一个抽象的Registrar基类,该基类具体实现子类,然后遍历其__subclasses__()并调用is_registrar_for()类方法:

The more interesting question is how do you determine which registrar to load? One option is to have an abstract base Registrar class which concrete implementations subclass, then iterate over its __subclasses__() calling an is_registrar_for() class method:

class Registrar(object):
  def __init__(self, domain):
    self.domain = domain

class RegistrarA(Registrar):
  @classmethod
  def is_registrar_for(cls, domain):
    return domain == 'foo.com'

class RegistrarB(Registrar):
  @classmethod
  def is_registrar_for(cls, domain):
    return domain == 'bar.com'


def Domain(domain):
  for cls in Registrar.__subclasses__():
    if cls.is_registrar_for(domain):
      return cls(domain)
  raise ValueError


print Domain('foo.com')
print Domain('bar.com')

这将使您透明地添加新的Registrar并将其各自支持的域委托给他们.

This will let you transparently add new Registrars and delegate the decision of which domains each supports, to them.

这篇关于Python中的类工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆