sayiwanttocompare2variableswithdifferentdatatypes : stringandint.ihavetesteditbothinpython2.7.3and python3.2.3aned ned onisfalse.caniconfigureorrunpythonwithdifferentoptionstothrowexceptioninthiscase?
ks@ks-P35-DS3P:~$ python2
python2.7.3(默认,aug 12012,05336014336039 )。
[GCC 4.6.3] on linux2
Type 'help '、' copyright '、' credits ' or ' license ' for more information。
a='123 '
b=123
a==b
假的
ks@ks-P35-DS3P:~$ python3
python3.2.3(默认,apr 122012,19336008336059 )。
[GCC 4.6.3] on linux2
Type 'help '、' copyright '、' credits ' or ' license ' for more information。
a='123 '
b=123
a==b
假的
ks@ks-P35-DS3P:~$
No,you can ' t.theitemsarejustnotequal,there is no error there。
通用快递,itisunpythonictoforceyourcodetoonlyacceptspecifictypes.whatifyouwantedtocreateasubclassoftheint, andhavavictedtocreateasubclassoftheint thepythonbooleantypeisasubclassofint,forexample(true==1,False==0)。
If you have to have an exception,you can do one of two things:
testforequalityontheirtypesandraiseanexceptionyourself :
ifnotisinstance(a,type(b ) ) and not isinstance(b,type(b ) ) :
raise typeerror (通告类型) )。
if a==b:
# .
thisexampleallowsforeitheraorbtobeasubclassoftheothertype,you ' dneedtonarrowthatdownasneeded (类型(a ) is类型(b ) ) )
三至订单the types :
if not a b and not a b:
# .
In Python 3,thisthrowsanexceptionwhencomparingnumericaltypeswithsequencetypes (suchas strings ).thecomparisonsucceeeeedinpyths
Python 3 demo:
A,b=1,'1'
not a b and not a b
跟踪后退(mostrecentcalllast ) :
文件',line 1,in
a,b=1,1
not a b and not a b
真的