Python 中 .Net InvalidOperationException 的模拟是什么?

发布于 2024-08-28 00:14:40 字数 80 浏览 8 评论 0原文

Python 中 .Net InvalidOperationException 的模拟是什么?

What is the analog for .Net InvalidOperationException in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

辞取 2024-09-04 00:14:40

没有直接的等价物。通常 ValueErrorTypeError 就足够了,如果这两者都不适合,也许是 RuntimeErrorNotImplementedError

There's no direct equivalent. Usually ValueError or TypeError suffices, perhaps a RuntimeError or NotImplementedError if neither of those fit well.

薆情海 2024-09-04 00:14:40

我可能会选择以下两个选项之一:

  1. 自定义异常,最好定义如下:

    类InvalidOperationException(异常):
    通过

  2. Just using Exception

我不相信有直接的类似物; Python 似乎有一个非常扁平的异常层次结构。

I'd probably go between one of two options:

  1. A custom exception, best defined as follows:

    class InvalidOperationException(Exception):
    pass

  2. Just using Exception

I don't believe there's a direct analogue; Python seems to have a very flat exception hierarchy.

纸伞微斜 2024-09-04 00:14:40

我部分同意 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...

不过,我不同意抛出一个赤裸裸的“异常”。

I'll partially agree with Chris R -- define your own:

     class InvalidOperationException(Exception): pass

You get much benefit from defining your own exceptions this way, including building a hierarchy to fit your needs:

     class MyExceptionBase(Exception): pass
     class MyExceptionType1(MyExceptionBase): pass
     class MyExceptionType2(MyExceptionBase): pass
     # ...
     try:
        # something
     except MyExceptionBase, exObj:
        # handle several types of MyExceptionBase here...

I don't agree with throwing a naked "Exception", though.

小红帽 2024-09-04 00:14:40

在我看来,您应该这样做,

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 时,它尝试从 Matrix2D 调用 __mul__,但失败。当且仅当它返回 NotImplemented 时,它才会尝试从右侧的对象调用 __rmul__

In my opinion, you should do

return NotImplemented

instead of defining your own exception. See the example below for a case where this would be preferable:

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]

It should run without any error. When doing m*v, it tries to call __mul__ from Matrix2D, but fails. If, and only if, it returns NotImplemented, then it tries to call __rmul__ from the object on the right side.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文