InvalidOperationException
.Net in的类比是什么Python
?
问问题
3913 次
4 回答
20
没有直接的等价物。通常ValueError
orTypeError
就足够了,也许 aRuntimeError
或者NotImplementedError
如果两者都不合适。
于 2010-03-31T16:47:22.167 回答
9
我可能会在两个选项之一之间进行:
自定义异常,最好定义如下:
class InvalidOperationException(Exception): pass
只是使用
Exception
我不相信有直接的类似物。Python 似乎有一个非常扁平的异常层次结构。
于 2010-03-31T16:46:37.833 回答
4
我会部分同意 Chris R——定义你自己的:
class InvalidOperationException(Exception): pass
通过这种方式定义自己的异常,您将获得很多好处,包括构建一个层次结构以满足您的需求:
class MyExceptionBase(Exception): pass
class MyExceptionType1(MyExceptionBase): pass
class MyExceptionType2(MyExceptionBase): pass
# ...
try:
# something
except MyExceptionBase, exObj:
# handle several types of MyExceptionBase here...
不过,我不同意抛出一个赤裸裸的“异常”。
于 2010-03-31T22:31:06.870 回答
0
在我看来,你应该这样做
return NotImplemented
而不是定义自己的异常。请参阅下面的示例以了解更可取的情况:
class InvalidOperationException(Exception):
pass
class Vector2D(list):
def __init__(self, a, b):
super().__init__([a, b])
def __add__(self, other):
return Vector2D(self[0] + other[0],
self[1] + other[1])
def __mul__(self, other):
if hasattr(other, '__len__') and len(other) == 2:
return self[0]*other[0] + self[1]*other[1]
return Vector2D(self[0]*other, self[1]*other)
def __rmul__(self, other):
if hasattr(other, '__len__') and len(other) == 2:
return Vector2D(other[0]*self, other[1]*self)
return Vector2D(other*self[0], other*self[1])
class Matrix2D(list):
def __init__(self, v1, v2):
super().__init__([Vector2D(v1[0], v1[1]),
Vector2D(v2[0], v2[1])])
def __add__(self, other):
return Matrix2D(self[0] + other[0],
self[1] + other[1])
def __mul__(self, other):
# Change to:
# return InvalidOperationException
# or:
# raise InvalidOperationException
return NotImplemented
if __name__ == '__main__':
m = Matrix2D((1, -1),
(0, 2))
v = Vector2D(1, 2)
assert v*v == 5 # [1 2] [1] = 5
# [2]
assert v*m == Vector2D(1, 3) # [1 2] [1 -1] = [1 3]
# [0 2]
try:
result = m*m
print('Operation should have raised a TypeError exception, '
'but returned %s as a value instead' % str(result))
except TypeError:
pass
assert m*v == Vector2D(-1, 4) # [1 -1] [1] = [-1]
# [0 2] [2] [ 4]
它应该运行没有任何错误。这样做时m*v
,它会尝试调用__mul__
from Matrix2D
,但失败了。当且仅当它返回 时NotImplemented
,它会尝试__rmul__
从右侧的对象调用。
于 2019-06-06T11:44:50.877 回答