如果您将 int 对象包装在自定义子类中,则可以处理一次:
class SafeInt(int):
def __div__(self, y):
try:
return SafeInt(super(SafeInt, self).__div__(y))
except ZeroDivisionError:
return SafeInt(0)
覆盖所有 ints:
original_int = int
int = SafeInt
int(5) / 0
# O: 0
覆盖一些 ints:
SafeInt(5) / 0
# O: 0
您必须小心保持对象为 SafeInt。你会注意到我在__div__ 中返回的所有内容都包含在SafeInt() 中。 int 对象是不可变的,您每次都必须显式返回一个新的 SafeInt 对象。这意味着您可能需要为SafeInt() 中的每个函数制作一个装饰器以确保这一点。我把它作为练习留给读者!
否则你会得到这样的结果:
>>> SafeInt(5) / 0
0 # this is a SafeInt object
>>> _ / 0
0 # this is a SafeInt object; no error
>>> SafeInt(5) + 0
5 # this is a basic int object
>>> _ / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
最后一点:您可以将SafeInt 作为defaultdict 的参数传递给所有成员SafeInt!
编辑:知道你希望它发生在 all ints,我希望这样的事情可能会起作用,但它是不允许的(有充分的理由):
>>> def wrapdiv(olddiv):
... def newdiv(self, y):
... try:
... olddiv(self, y)
... except ZeroDivisionError:
... return 0
... return newdiv
...
>>> int.__div__ = wrapdiv(int.__div__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'int'