生成对象或对象列表的对象工厂
我有以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于您将如何处理该列表。这是最简单的方法:
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
如果大多数情况最好通过调用
cls
来处理,而少数情况最好通过其他方式处理,那么最简单的方法就是挑出后者:请注意,调用
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: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.