[英]Python: Why does equality comparing an int with a string not throw an error?
In Python 3 the attempt to order a string and an int (eg 1 > "1"
) throws a TypeError. 在Python 3中,尝试对字符串和int(例如
1 > "1"
)进行排序会引发TypeError。 Why does comparing a string with an int for equality not throw an error? 为什么比较字符串和int的相等性不会抛出错误? (eg
1=="1"
) What is an example where comparing a string with an int makes sense? (例如
1=="1"
)将字符串与int进行比较有什么意义? Why do JavaScript and SQL take a different approach? 为什么JavaScript和SQL采用不同的方法?
Related: How does Python compare string and int? 相关: Python如何比较字符串和int?
This allows you, for example, to have a dictionary with keys of mixed types. 例如,这允许您拥有包含混合类型键的字典。
If you couldn't compare 1
and "1"
for equality, you wouldn't be able to use them as keys into the same dictionary. 如果您无法比较
1
和"1"
的相等性,则无法将它们用作同一字典中的键。
As things stand, you can compare them, and they always compare unequal : 事实上,你可以比较它们,它们总是比较不平等 :
The objects need not have the same type.
对象不必具有相同的类型。 If both are numbers, they are converted to a common type.
如果两者都是数字,则将它们转换为通用类型。 Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.
否则,不同类型的对象总是比较不相等,并且一致但是任意地排序。
The reason the orderings raise TypeError
on non-comparable objects is to represent that there is no sensible answer , rather than any prediction on whether it would ever be useful. 排序在非可比较对象上引发
TypeError
的原因是表示没有合理的答案 ,而不是任何关于它是否有用的预测。 Allowing an equality test is sensible by this logic, insofaras there is an answer for "are two non-comparable objects equal?" 允许一个平等的测试是明智的这一逻辑,insofaras 有回答“是两个不可比较的对象平等的吗?” (they aren't).
(他们不是)。 See, eg, http://www.gossamer-threads.com/lists/python/dev/919516 .
参见,例如, http : //www.gossamer-threads.com/lists/python/dev/919516 。
Typing of language could be strong or weak (loose). 语言的输入可能是强弱的(松散的)。 The stronger typing language has the less different types could be operated in the same operation.
更强的打字语言在同一操作中可以操作的类型越少。 Weakness and strength of language typing don't have exact threshold - some language could have stronger typing then other and weaker than another one.
语言输入的弱点和强度没有确切的阈值 - 某些语言可能比其他语言具有更强的类型,而弱于另一种语言。 Python typing is much stronger than JS .
Python打字比JS强大得多 。
==
implemented as more of less weakly-typed operation. ==
实现更少弱类型的操作。 It can compare different types but you need to have both values of the same type to have a chance to obtain True
. 它可以比较不同的类型,但您需要具有相同类型的两个值才有机会获得
True
。 a == b #true
means a
and b
is objects of the same type and have the equal values. a == b #true
表示a
和b
是相同类型的对象,并且具有相等的值。 >
<
in Python 3 implemented as strongly-typed operation and couldn't be performed on different types. >
<
在Python 3中实现为强类型操作,无法在不同类型上执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.