使用算术运算符比较无内置类型? [英] Comparing None with built-in types using arithmetic operators?

查看:121
本文介绍了使用算术运算符比较无内置类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> None > 0
False
>>> None == 0
False
>>> None < 0
True




  • 比较使用为内置类型(在这种情况下为整数)定义的算术运算符?

  • 语言规范的前两个和第三个比较部分之间的区别(Python的规范 - 你一定是开玩笑:)或者是CPython的实现细节?

    • Is comparing None using arithmetic operators well defined for built-in types (integers in this case)?
    • Is the difference between the first two and the third comparison part of language specification (Python's specification - you must be kidding :)) or is it CPython's implementation detail?
    • 推荐答案

      None if obj is None:(或如果obj不是None:)。

      不同类型之间的比较已经从Python 3中删除了好的原因 - 他们是一个常见的错误源,导致混乱。例如

      Comparison between different types has been removed from Python 3 for good reasons - they were a common source of errors and lead to confusion. For example

      >>> "3" < 4
      False
      



      在Python 3中,你会得到一个 TypeError 比较 str int 或任何与

      >>> None < 0
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      TypeError: unorderable types: NoneType() < int()
      

      (我的意思是比较,试图确定两个值如果两个对象是不同类型的,它们总是返回 False 。)

      (I mean "comparing" in the sense of trying to determine which of two values is larger/smaller. Comparison for equality is OK - it will always return False if two object are of different types.)

      我在文档中找不到此引用,但在学习Python,第4版中,Mark Lutz在第204页写道:

      I haven't found a reference in the docs for this, but in Learning Python, 4th edition, Mark Lutz writes on page 204:


      [...]比较不同类型的对象(例如,字符串和
      列表)工作 - 语言定义不同
      类型之间的固定排序,这是确定性的,如果不是美学上令人愉快的。也就是说,
      的排序是基于所涉及的类型的名称:所有整数
      小于所有字符串,例如,因为int小于
      str

      这篇关于使用算术运算符比较无内置类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆