用于布尔值的比较运算符

Comparison operators used for Boolean values

比较运算符如何工作?我认为它们只能用于比较数值,5 <= 8 等。但是在这段代码中 sets 被比较:

str = 'The quick Brow Fox'
alphabet = string.ascii_lowercase
alphaset = set(alphabet)

b = alphaset <= set(str.lower()) # Does it automatically extract length of objects?

print(len(alphaset))  # 26
print(len(set(str.lower())))  # 19
print(b)

26
15
False

我认为这是不可能的。 alphaset <= set(str.lower()),字面意思就是,e。 G。 set() <= set()。运算符是否在此类对象上隐式调用 len() 以查找要比较的数值?

它如何知道一个序列大于、小于或等于另一个序列?

来自Python manual

issubset(other)
set <= other

       Test whether every element in the set is in other.

有多种magic methods you can implement if you want to overload operators for your own classes. When you call a < b Python defers to a.__le__(b)如果有这样的方法。

Python 支持 operator overloading,这意味着任何 class 都可以实现提供对标准运算符的访问的方法。

有关您可以在 Python 中执行的操作的完整文档,包括 class 可以实施哪些方法来支持不同的运算符,请查看 Python data model

有关 set 等内置类型如何实现其运算符的说明,请参阅该类型的文档。例如,documentation for the set type.