【发布时间】:2015-09-17 21:52:26
【问题描述】:
我有一个 Python 函数,它可以返回两种类型的返回值之一,animal 或 food。两者都是字符串类型。现在,我通过总是返回两个值来区分两者,断言其中只有一个是True:
def help(x):
if some_condition(x):
return 'monkey', None
elif # ...
animal = some_fantasy_animal(x)
return animal, None
elif #..
food = some_food_no_one_has_ever_heard_of(x)
return None, food
elif # ...
return None, 'steak'
# ...
def main():
animal, food = help('ddd')
if animal:
assert(not food)
# do something useful
pass
else:
assert(food)
# do something useful
pass
return
必须有更好的方法来处理这个问题。有哪些选择?
【问题讨论】:
-
什么是动物和食物?
-
实际上,我用于构建配置文件的字符串。根据类型,它们承担不同的角色。
animal-food的隐喻就是抽象掉这个。 -
它们是类的实例吗?
-
是的,他们都是
strings。 -
好的,我明白你在做什么,我会使用类来区分你的对象,让你的生活更轻松。
标签: python class return return-value