【问题标题】:type(4) == type(int) is False in Python?type(4) == type(int) 在 Python 中是 False 吗?
【发布时间】:2016-10-26 16:27:00
【问题描述】:

我试过type(4) == type(int),它返回False,但print type(4)返回<type 'int'>,所以4显然是int

对为什么第一条语句返回False而不是True感到困惑?

【问题讨论】:

  • type(int)type...
  • @MartijnPieters,不错的收获并投票。但是如何检查类型是否为整数?我想区分 int、float/double 和非数字。
  • @LinMa isinstance(num,int)

标签: python python-2.7 types integer


【解决方案1】:

看这个:

>>> type(int)
<type 'type'>
>>> type(4)
<type 'int'>

你应该使用:

>>> isinstance(4,int)
True

【讨论】:

    【解决方案2】:

    inttype类型本身

    >>> type(int)
    <type 'type'>
    

    你会和int直接比较; int 毕竟是一种类型,正如我们在上面建立的:

    >>> type(4) == int
    True
    

    甚至,因为int 是一个单例,所以所有类型都应该是:

    >>> type(4) is int
    True
    

    但是,测试类型的正确方法是使用 isinstance() function:

    >>> isinstance(4, int)
    True
    

    isinstance() 还允许int任何子类 通过此测试;一个子类总是被认为是至少一个int。这包括您可以自己构建的任何自定义子类,并且仍然可以在代码中的其他任何地方将其作为int 工作。

    【讨论】:

    • 我也学到了同样的东西(更喜欢isinstance而不是type()==);然而,读到这里,type(number)==int 感觉 更 Pythonic。如果您能谈谈为什么 isinstance 是正确的方法,那就太好了。
    【解决方案3】:

    在Python中,类型int本身也是一个类型为type的对象。所以type(int)type。另一方面,type(4)int

    所以如果你想检查type(4)是否是int类型,你应该写成

    type(4) == int
    

    【讨论】:

      【解决方案4】:

      您将inttype(int) 进行比较,您应该:

      type(4) == int
      

      【讨论】:

        【解决方案5】:

        type of inttypetype of 4int

        >>> type(int)
        <type 'type'>
        >>> type(4)
        <type 'int'>
        

        所以你做了错误的比较。 要获得所需的输出,您可以做的是: 比较type of 4int

        >>> type(4) == int
        True
        

        或者你可以使用is 操作符

        >>> type(4) is int
        True
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-19
          • 2016-05-23
          • 2013-06-02
          • 2012-08-20
          • 1970-01-01
          • 2014-04-26
          • 1970-01-01
          • 2011-03-11
          相关资源
          最近更新 更多