可以让Python在比较不同数据类型时抛出异常吗?

10 投票
3 回答
7030 浏览
提问于 2025-04-17 19:20

假设我想比较两个不同类型的变量:一个是字符串(string),另一个是整数(int)。我在Python 2.7.3和Python 3.2.3中都测试过,结果是都没有抛出异常。比较的结果是 False。我可以通过什么方式来设置或运行Python,让它在这种情况下抛出异常吗?

ks@ks-P35-DS3P:~$ python2
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a="123"
>>> b=123
>>> a==b
False
>>> 
ks@ks-P35-DS3P:~$ python3
Python 3.2.3 (default, Apr 12 2012, 19:08:59) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a="123"
>>> b=123
>>> a==b
False
>>> 
ks@ks-P35-DS3P:~$ 

3 个回答

0

你可以定义一个函数来实现这个功能:

def isEqual(a, b):
    if not isinstance(a, type(b)): raise TypeError('a and b must be of same type')
    return a == b # only executed if an error is not raised
1

我想不出一个方法可以做到这一点,而且不会让人觉得使用起来太麻烦。这是一个需要小心数据类型的情况,而Python在这方面没有给我们太多帮助。

你应该感到庆幸,因为你不是在使用那种数据类型会在字符串和整数之间悄悄转换的语言。

8

不,你不能这样做。这些项目本身就是不相等的,这里没有错误。

一般来说,强迫你的代码只接受特定类型的做法是不符合Python风格的。比如说,如果你想创建一个int的子类,并希望它在任何需要int的地方都能正常工作,那该怎么办呢?举个例子,Python中的布尔类型就是int的子类(True等于1,False等于0)。

如果你必须处理异常情况,可以选择以下两种方法之一:

  1. 检查它们的类型是否相等,并自己抛出一个异常:

    if not isinstance(a, type(b)) and not isinstance(b, type(a)):
        raise TypeError('Not the same type')
    if a == b:
        # ...
    

    这个例子允许成为另一个类型的子类,你需要根据需要进一步限制(type(a) is type(b)会非常严格)。

  2. 尝试对类型进行排序

    if not a < b and not a > b:
        # ...
    

    在Python 3中,当比较数字类型和序列类型(比如字符串)时,会抛出异常。而在Python 2中,这种比较是成功的。

    Python 3示例:

    >>> a, b = 1, '1'
    >>> not a < b and not a > b
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unorderable types: int() < str()
    >>> a, b = 1, 1
    >>> not a < b and not a > b
    True
    

撰写回答