Python 3中是否存在类似Python 2里None的小于任意数字的对象?
Python 3中是否存在始终小于任意数字的对象?
在Python 2中,None类型被设定为小于任何对象,因此对任意数字x,执行以下代码都会返回True:
>>> None < x True
但Python 3移除了这种跨类型的默认比较逻辑,不同类型(除了有明确比较规则的数值子类)之间直接使用<比较会抛出TypeError,比如执行None < 5就会报错:
>>> None < 5 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '<' not supported between instances of 'NoneType' and 'int'
Python 3的标准库中并没有内置的、能始终小于任意数字的对象,但你可以自己定义一个类,通过实现__lt__方法来实现这个功能:
class AlwaysLess: def __lt__(self, other): # 仅针对数字类型返回True,也可以直接返回True让它小于所有对象 return isinstance(other, (int, float, complex)) # 创建实例 always_less = AlwaysLess() # 测试 print(always_less < 10) # 输出 True print(always_less < -100.5) # 输出 True print(always_less < 3+4j) # 输出 True
内容的提问来源于stack exchange,提问作者VanDerGraaf
相关产品推荐
相关产品推荐

