python中的Error-checking策略

  [b]参考 python in nutshell 的第三版.[/b]

1.在python中异常被认为无论什么时候只要能使程序更简单更强大就可以被使用。甚至异常可以被频繁的抛出.

2.在很多语言中,他们所遵从的是"look before you leap" (LBYL),也就是说,在尝试一个操作之前首先应该先检查一下.这里我的理解就是LBYL只是关心语法而不是关心语义的表达。可是python中遵从的是"it's easier to ask forgiveness than permission"既(EAFP),这也是cobol所遵从的,呵呵我在这里的理解是什么都不管先做再说。EAFP更注重语义的表达。
   
  可以通过代码来比较LBYL与EAFP的不同,按照LBYL中我们的代码可能是这样

[code]
def safe_divide_1(x, y):
if y==0:
print "Divide-by-0 attempt detected"
return None
else:
return x/y
[/code]
  
  而按照EAFP我们的代码就是这样:
[code]
def safe_divide_2(x, y):
try:
return x/y
except ZeroDivisionError:
print "Divide-by-0 attempt detected"
return None
[/code]
  
 3而在使用EAFP风格的时候要注意使用else,比如下面的代码:
[code]
def trycalling(obj, attrib, default, *args, **kwds):
try: return getattr(obj, attrib)(*args, **kwds)
except AttributeError: return default
[/code]
在这个代码中当如果当getattr的传进多个参数时程序就会出错,因此代码应当改为下面的
[code]
def trycalling(obj, attrib, default, *args, **kwds):
try: method = getattr(obj, attrib)
except AttributeError: return default
else:return method(*args,**kwds)
[/code]
 4 在python in nutshell 中,作者提出了LBYL的几点不足:

[quote]
The checks may diminish the readability and clarity of the common, mainstream cases where everything is okay.

The work needed for checking may duplicate a substantial part of the work done in the operation itself.

The programmer might easily err by omitting some needed check.

The situation might change between the moment the checks are performed and the moment the operation is attempted.
[/quote]

感觉作者很是推崇EAFP,不知道各位怎么看LBYL和EAFP?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值