ks1*_*322 5 python error-handling types exception
假设我想比较两个不同数据类型的变量: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:~$
Run Code Online (Sandbox Code Playgroud)
不,你不能.这些项目不相等,那里没有错误.
一般来说,强制您的代码只接受特定类型是非常规的.如果你想创建一个子类int,并让它在任何地方工作,该int怎么办?Python布尔类型是int例如(True== 1,False== 0)的子类.
如果您必须有例外,您可以执行以下两项操作之一:
测试其类型的相等性并自己引发异常:
if not isinstance(a, type(b)) and not isinstance(b, type(a)):
raise TypeError('Not the same type')
if a == b:
# ...
Run Code Online (Sandbox Code Playgroud)
这个例子允许a或b成为另一个类型的子类,你需要根据需要缩小它(type(a) is type(b)超级严格).
尝试订购类型:
if not a < b and not a > b:
# ...
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)您可以定义一个函数来执行此操作:
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
Run Code Online (Sandbox Code Playgroud)