在Python2.7上与无比较时如何抛出异常?

2024-04-26 23:06:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python 2.7中:

表达式1(精细):

>>> 2 * None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

表达式2(精细):

>>> None is None
True

表达式3():

>>> 2 < None
False

表达式4():

>>> None<None
False

表达式5():

>>> None==None
True

我想以某种方式强制表达式3、4和5抛出TypeError(与表达式1相同)。你知道吗

Python3.4就快到了-只有表达式5返回True。你知道吗

我需要2.7版。你知道吗


我的用例(如果有人感兴趣):

I'v制作了一个计算一些表达式的应用程序(示例):

d = a+b
e = int(a>b)
f = a if a<b else b if b<c else c

表达式基于来自反序列化json的值(a、b和c)。大多数时间值(a、b和c)都是整数,但有时(缺少值时)它是零。当值丢失并且在某些表达式中使用时,表达式应该返回None(我正在考虑捕获TypeError异常)。

如果a=None,b=1,c=2,则导出结果为:d=None,e=None,f=None。

如果a=1,b=2,c=None,预期结果为:d=3,e=0,f=1


Tags: nonefalsetruemostif表达式stdincall
2条回答

您可以使用isInstance:

from numbers import Number


def pre(a, b, c):
    if not isinstance(a, Number) or not isinstance(b, Number):
        return None, None, None
    if not isinstance(c, Number):
        return a + b, a > b, a if a < b else b
    return a + b, a > b,  a if a < b else b if b < c else c

如果计算中的任何数字为“无”,则返回所有“无”,如果c为“无”,则返回不包括If b<;c else c的计算,如果它们都是数字,则返回所有表达式:

In [53]: pre(None,1,2)
Out[53]: (None, None, None)

In [54]: pre(1,2,None)
Out[54]: (3, False, 1)

In [55]: pre(None,None,None)
Out[55]: (None, None, None)

In [56]: pre(3,4,5)
Out[56]: (7, False, 3)

无法更改None的行为。但是,您可以实现自己的类型,该类型具有所需的行为。作为起点:

class CalcNum(object):
    def __init__(self, value):
        self.value = value

    def __add__(self, o):
        return CalcNum(self.value + o.value)

    def __lt__(self, o):
        if self.value is None or o.value is None:
            # Pick one:
            # return CalcNum(None)
            raise TypeError("Can't compare Nones")

        return CalcNum(self.value < o.value)

相关问题 更多 >