python - type(4) == type(int) 在 Python 中是 False 吗?

标签 python python-2.7 types integer

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

困惑为什么第一个语句返回 False而不是 True

最佳答案

int类型类型本身:

>>> 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 工作。

关于python - type(4) == type(int) 在 Python 中是 False 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38006826/

相关文章:

python-2.7 - xlsxwriter模块中有flush方法吗? [Python 2.7]

python-2.7 - 在 models_committed 信号处理程序中的模型中使用 server_default 时出现 Flask SQLAlchemy 事务错误

Swift [1,2] 符合 AnyObject 但 [Enum.a, Enum.b] 不符合

python - Python 中二维矩阵的傅里叶变换

python - 如何在 Django 分页中加载 Stripe 对象

python - 如何使用 Python imaplib 将消息从一个 imap 服务器复制到另一个 imap 服务器?

python - 如何下载PyHook模块

python - 使用 python selenium 的网页抓取问题

Haskell 不在范围内 : Type constructor or class `PushInt'

varargs 方法的 Scala 类型边界