gpt4 book ai didi

python - Python 中 ZeroDivisionError 的好处

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:38 27 4
gpt4 key购买 nike

假设我有两个变量 x 和 y,它们可以是任何值。我必须将 x 除以 y。 y 可以为零。现在我有两种方法

1)

if y == 0:      
continue # or break, supposing there is a loop going on.

2)

try:
print 1/0
except ZeroDivisionError as e:
print e
finally:
print "got"

我的问题是,方法 2 是否比方法 1 有任何好处,如果有,那是什么?

最佳答案

try/except 可能 be slightly faster .

一般来说,“Pythonic 方式”是尝试做您想做的事情,如果它不起作用则处理错误(“Easier to Ask Forgiveness than Permission”),而不是预先检查(“Look Before You Leap”) "),以便在未来提供更大的灵 active 。

在您的代码中,y 似乎通常是一个整数(int 的实例)..但想象一下您的需求会发生变化,并且 y > 是 NewClass 的实例,现在可以保存类似 -0.0001 的值。

为了保持与您的应用程序的兼容性,编写了 NewClass.__eq__() 以便 if y == 0 将进行整数比较( 在此实例中为 True),但 NewClass.__truediv__ 使用浮点值,因此 1/y 不会返回一个错误。

因此,如果您使用 if,您的应用程序将表现得像 -0.0001 == 0 而使用 except ZeroDivisionError 将正确处理新行为.

class NewClass(int):
def __eq__(self, other):
return int(self) == int(other)
def __truediv__(self, other):
return self.value / other

y = NewClass(-0.0001)

if y != 0:
print 1 / y # not printed

try:
print 1 / y # printed
except ZeroDivisionError:
pass

关于python - Python 中 ZeroDivisionError 的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32567119/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com