生成对象或对象列表的对象工厂

发布于 2024-09-17 10:54:19 字数 643 浏览 5 评论 0原文

我有以下代码:

def f(cls, value):
  # cls is a class
  # value is a string value
  if cls == str:
    pass # value is already the right type
  elif cls == int:
    value = int(value)
  elif cls == C1:
    value = C1(value)
  elif cls == C2:
    value = C2(value)
  elif cls == C3
    # in this case, we convert the string into a list of objects of class C3
    value = C3.parse(value)
  else
    raise UnknownClass(repr(cls))
  return value

显然,我试图用类似的东西替换它:

def f(cls, value)
   return cls(value)

不幸的是,在某些情况下(如果 cls == C3),输入的解析结果是该类的对象列表,而不仅仅是一个物体。有什么巧妙的方法来处理这个问题?我可以访问所有课程。

I have the following code:

def f(cls, value):
  # cls is a class
  # value is a string value
  if cls == str:
    pass # value is already the right type
  elif cls == int:
    value = int(value)
  elif cls == C1:
    value = C1(value)
  elif cls == C2:
    value = C2(value)
  elif cls == C3
    # in this case, we convert the string into a list of objects of class C3
    value = C3.parse(value)
  else
    raise UnknownClass(repr(cls))
  return value

Obviously, I'm trying to replace it with something like:

def f(cls, value)
   return cls(value)

Unfortunately, in some cases (if cls == C3), the parsing of the input results in a list of objects of that class, rather than just one object. What's a neat way to handle this? I have access to all the classes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

兔姬 2024-09-24 10:54:23

这取决于您将如何处理该列表。这是最简单的方法:

obj = cls(value)

如果 type(obj) == list:

handle_list(obj)

返回 obj

That depends on what you'd do with the list. This is the simplest way:

obj = cls(value)

if type(obj) == list:

handle_list(obj)

return obj

思念满溢 2024-09-24 10:54:22

如果大多数情况最好通过调用cls来处理,而少数情况最好通过其他方式处理,那么最简单的方法就是挑出后者:

themap = {C3: C3.parse}
for C in (str, C1, C2):
    themap[C] = C

def f(cls, value):
    wot = themap.get(cls)
    if wot is None:
        raise UnknownClass(repr(cls))
    return wot(value)

请注意,调用str > 在字符串上是一个相当快的 noop,因此通常值得避免“挑出”该特定情况以支持代码简单性。

If most cases are best handled by calling cls, and a few are best handled otherwise, simplest is to single out the latter:

themap = {C3: C3.parse}
for C in (str, C1, C2):
    themap[C] = C

def f(cls, value):
    wot = themap.get(cls)
    if wot is None:
        raise UnknownClass(repr(cls))
    return wot(value)

Note that calling str on a string is a pretty fast noop, so it's generally worth avoiding the "singling out" of that specific case in favor of code simplicity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文