严格比较 [英] Strict comparison
问题描述
在 javascript 中,有严格的比较运算符 op1 === op2
和 op1 !== op2
将比较类型和值.有没有一种pythonic的方式来实现同样的事情?
In javascript, there are strict comparison operators op1 === op2
and op1 !== op2
that will compare both type and value. Is there a pythonic way of achieving the same thing?
到目前为止,我只能想出以下凌乱的条件:
So far I've only been able to come up with the following messy conditionals:
isinstance(op1, type(op2)) and isinstance(op2, type(op1)) and op1 == op2
和
not isinstance(op1, type(op2)) or not isinstance(op2, type(op1)) or op1 != op2
推荐答案
您的方法确实会检查值和类型.Python 中没有不同的运算符.
Your approach would indeed check both value and type. There isn't a different operator in Python.
话虽如此,在很多情况下这不是您想要的 - 在 Python 的哲学中,任何表现得像鸭子的对象都应该被视为鸭子.您通常不仅需要字典,还需要类似映射"的对象等等——只要该对象可以用于特定任务,那么代码就应该接受它.
This having been said, in many cases that's not what you want - in Python's philosophy any object that behaves as a duck should be treated as a duck. You often don't want only dictionaries, you want "mapping-like" objects and so on - as long as the object can be used for the particular task then the code should accept it.
这篇关于严格比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!