InvalidOperationException
中.Net Python
的模拟内容是什么?
答案 0 :(得分:12)
没有直接的等价物。通常ValueError
或TypeError
就足够了,如果两者都不合适,可能是RuntimeError
或NotImplementedError
。
答案 1 :(得分:5)
我可能介于两个选项之一:
自定义异常,最佳定义如下:
class InvalidOperationException(Exception):
pass
只需使用Exception
我不相信有直接的模拟; Python似乎有一个非常平坦的异常层次结构。
答案 2 :(得分:3)
我将部分同意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...
但是,我不同意抛出赤裸裸的“例外”。
答案 3 :(得分: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__
调用Matrix2D
,但失败。当且仅当它返回NotImplemented
时,它才会尝试从右侧的对象调用__rmul__
。