python中的最佳返回类型策略

2024-04-30 05:40:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在为下一个问题寻找一个“按计划行事”的解决方案:

我有一个名为InputChecker的类,它接受一个输入文件,检查它的内容,如果一切正常,将该文件返回给下一个类(ExpofitAgent)进行进一步操作。在

但是,如果文件的格式不是它应该的格式,InputChecker会生成一条错误消息,说明在文件的哪一行发现了错误。在

InputChecker不打印错误,它只生成稍后打印的消息。在

因为我是用python编写的,所以我的方法可以返回一个文件或一个字符串。如何在不需要附加标志的情况下检查文件是否正常?在


Tags: 文件方法字符串消息内容标志格式错误
2条回答

引发异常:http://docs.python.org/tutorial/errors.html

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal... Most exceptions are not handled by programs, however, and result in error messages...

我很难想象使用异常的Marcin's answer不是最好的答案。在

但是,如果您确实需要一个替代方法,那么在Python中使用tuple一次返回多个内容是很容易的。在

def myfunc():
    # ...
    if file_is_ok:
        return myfile, None
    else:
        return None, error_string

mf, es = myfunc()
if es:
    # show error string

相关问题 更多 >