Python3 中的比较运算符使用问题
最近看到 Python 官方文档时,在标准库中的内置类型的比较部分卡住了,有一段感觉不是很明白,摘抄如下:
Objects of different types, except different numeric types, never compare equal. Furthermore, some types (for example, function objects) support only a degenerate notion of comparison where any two objects of that type are unequal. The <, <=, > and >= operators will raise a TypeError exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering
原文在 https://docs.python.org/3/library/stdtypes.html#comparisons 那个表格的下面那一段,主要是那一句:Furthermore, some types (for example, function objects) support only a degenerate notion of comparison where any two objects of that type are unequal.
这个degenerate notion of comparison是什么?字面理解的话好像是退化的比较概念,或者说是简化版的比较,这个指的是什么?
已知的是:Python3 中不同类型的比较好像只有不同的数字类型能比较,而且复数也不能和其他的数字类型比较,其他的不同类型之间好像只能用"==","!=","is","is not"比较。
Python2 中不同类型好像根据 id 来比较的,参考: Stack Overflow
可能有点钻牛角尖了,请各位大神能指点一二,谢谢了。
Python3 中的比较运算符使用问题
Furthermore, some types (for example, function objects) support only a degenerate notion of comparison where any two objects of that type are unequal.
对于某些类型只支持部分的比较,即任意两个该类型的对象都是不等的。就是说,只支持==和!=,并且是比较其 id
后面那段话意思是<, <=, >, >=的比较符在下列情况会抛出 TypeError
1. 比较一个复数类型和其他类型的数字
2. 对象属于不能比较的不同类型
3. 对象的类型没有定义比较的方法(lt, le, gt, ge)
Python3里的比较运算符其实挺直观的,就是用来比较两个值,返回True或False。常用的有等于(==)、不等于(!=)、大于(>)、小于(<)、大于等于(>=)和小于等于(<=)。
这里有个关键点:比较运算符可以链式使用,比如 a < b < c 在Python里是合法的,它等价于 a < b and b < c。这个特性用起来很方便。
另外,对于不同的数据类型,比较的规则不太一样:
- 数字之间就是比大小。
- 字符串是按字典序(就是一个个字符比Unicode码点)。
- 列表、元组这些序列也是按顺序比较元素。
- 对于自定义的类,你需要定义
__eq__,__lt__这些魔术方法来自定义比较行为。
注意别把赋值(=)和比较相等(==)搞混了,这是新手常犯的错误。
一句话建议:搞清链式比较和不同数据类型的比较规则,用的时候多留心。
a degenerate notion of comparison where any two objects of that type are unequal
… where any two objects of that type are unequal
就是只有比较是否是同一个对象的功能,没有比较不同对象是否语义上相等,也就是 object.ReferenceEquals
谢谢
嘿~,不知道你是用的什么字典,查单词不翻墙我一般用 柯林斯
https://www.collinsdictionary.com/zh/dictionary/english/degenerate
这是柯林斯查的 degenerate 的意思,第二条中说 degenerate 可以来形容低标准行为的人,同义词中有个 base,应该可以理解为"基础"。所以:
degenerate notion of comparison
应该可以理解为:
基础(基本)的比较。
希望有所帮助。
我看文档不懂的时候一般使用 Google 翻译的插件,一般都能了解个大概,没怎么查过具体的某个单词,所以没怎么用过词典,不过谢谢你的推荐,收藏了
这是个好问题:
def func1(): pass
def func2(): pass
# You can do this
assert func1 != func2
# But not this
func1 > func2
# TypeError: ‘>’ not supported between instances of ‘function’ and ‘function’
“Degenerate” as in “not fully featured”; it mentions that you can check that functions are unequal, but you can’t check whether one function is “greater than” another one. assert was only in my example to show that func1 != func2 is in fact True; you could leave out the assert and you’d just lose the result of the comparison — Zachary Ware

