python - 在 "if"语句的返回元组中使用 bool 值?

标签 python python-2.7

现状:

def isTooLarge(intValue):
  if intValue > 100: print "too large"; return True
  return False

if isTooLarge(101): break

现在我想通过返回错误消息文本而不是打印它来使函数更加“库友好”:

def isTooLarge(intValue):
  if intValue > 100: return True, "too large"
  return False

bln,str = isTooLarge(101)
if bln: specialprint(str); break

知道我如何才能再次将其评估为一句台词吗? (类似于“if ,str isTooLarge(101):specialprint(str);break”或者这里的Python方式是什么?

将错误消息放入像“lasterrormessage”这样的全局变量中并保持其余部分不变是没有问题的。

最佳答案

通过使用错误,就像错误一样,您可以更加“图书馆友好”:

def CheckNotTooLarge(intValue):
    if intValue > 100:
        raise ValueError("too large") #or AssertionError
    return #or maybe do something else?

然后用户可以使用 try: except: 完全单独地使用错误消息

try:
   CheckNotTooLarge(101)
except ValueError:
    traceback.print_exc() #print error message
    #handle too large
else:
    #handle not too large

我可以看到,如果您只想检查而不处理错误,这会很快变得烦人,因此我建议使用两个函数,一个仅返回 bool 值,不需要额外的工作,另一个则引发/返回错误文本:

def isTooLarge(intValue):
    return intValue<=100 #now this is a one liner!

def checkIsTooLarge(intValue):
    "uses isTooLarge to return an error text if the number is too large"
    if isTooLarge(intValue):
       return "too large" #or raise ...
    else:
       return False

关于python - 在 "if"语句的返回元组中使用 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38666852/

相关文章:

Python 导入在 Windows 中失败,但在 Linux 中不会

python - 可以在不模拟对象的其他属性的情况下模拟 python 构造函数吗?

python - 当 parentWidget 关闭时, float QDockWidget 不会关闭

python - 具有混合编码的文件 - Python

python - 如何使用plotly python绘制时间序列堆积条形图

python-2.7 - 将curl示例转换为pycurl

Python 2.7 和 ANTLR4 : Make ANTLR throw exceptions on invalid input

python - 正则表达式返回 true 且日文字符不正确

python - pymongo 中的 Tailable 游标似乎已停止工作

python - 如何查找 3d numpy 数组每列中连续 1 的组数