KT1*_*100 2 python python-2.7 python-3.x
我在Python中有一个类函数,它返回成功或失败,但如果发生故障,我希望它返回一个特定的错误字符串.我有三种方法:
将变量error_msg传递给最初设置为None的函数,如果出现错误,则将其设置为错误字符串.例如:
if !(foo(self, input, error_msg)):
print "no error"
else:
print error_msg
Run Code Online (Sandbox Code Playgroud)从函数返回包含bool和error_msg的元组.
我在出现错误时引发异常并在调用代码中捕获它.但是由于我没有看到我正在使用的代码库中经常使用异常,所以不太确定采用这种方法.
Pythonic的做法是什么?
创建自己的异常并改为:
class MyValidationError(Exception):
pass
def my_function():
if not foo():
raise MyValidationError("Error message")
return 4
Run Code Online (Sandbox Code Playgroud)
然后,您可以将您的功能称为:
try:
result = my_function()
except MyValidationError as exception:
# handle exception here and get error message
print exception.message
Run Code Online (Sandbox Code Playgroud)
这种风格称为EAFP("更容易要求宽恕而非许可"),这意味着您可以正常编写代码,在出现问题时引发异常并在以后处理:
这种常见的Python编码风格假设存在有效的键或属性,并且如果假设被证明是错误则捕获异常.这种干净和快速的风格的特点是存在许多try和except语句.该技术与许多其他语言(如C)共有的LBYL风格形成对比.
提出错误:
if foo(self, input, error_msg):
raise SomethingError("You broke it")
Run Code Online (Sandbox Code Playgroud)
处理它:
try:
something()
except SomethingError as e:
print str(e)
Run Code Online (Sandbox Code Playgroud)
这是Pythonic方法,最具可读性.
返回一个像元组(12, None)似乎是一个很好的解决方案,但是如果你不一致的话,很难跟踪每个方法返回的内容.返回两种不同的数据类型更糟糕,因为它可能会破坏假定数据类型恒定的代码.
| 归档时间: |
|
| 查看次数: |
7824 次 |
| 最近记录: |