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

Say I want to compare 2 variables with different data types: string and int. I have tested it both in Python 2.7.3 and Python 3.2.3 and neither throws exception. The result of comparison is False. Can I configure or run Python with different options to throw exception in this case?

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:~$

解决方案

No, you can't. The items are just not equal, there is no error there.

Generally speaking, it is unpythonic to force your code to only accept specific types. What if you wanted to create a subclass of the int, and have it work everywhere an int works? The Python boolean type is a subclass of int, for example (True == 1, False == 0).

If you have to have an exception, you can do one of two things:

Test for equality on their types and raise an exception yourself:

if not isinstance(a, type(b)) and not isinstance(b, type(a)):

raise TypeError('Not the same type')

if a == b:

# ...

This example allows for either a or b to be a subclass of the other type, you'd need to narrow that down as needed (type(a) is type(b) to be super strict).

Try to order the types:

if not a < b and not a > b:

# ...

In Python 3, this throws an exception when comparing numerical types with sequence types (such as strings). The comparisons succeed in Python 2.

Python 3 demo:

>>> a, b = 1, '1'

>>> not a < b and not a > b

Traceback (most recent call last):

File "", line 1, in

TypeError: unorderable types: int() < str()

>>> a, b = 1, 1

>>> not a < b and not a > b

True

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值