python - 如何在 Python 中正确检查对象类型?

标签 python types comparison isinstance

问题:我必须检查返回值是否是 Python 字典。

Q1。以下哪个选项是执行此操作的正确方法?

type(x) == dict

type(x) == type(dict)

isinstance(d, dict)

然后还有其他变体使用 is 运算符而不是 ==

Q2。 Many people说检查对象的类型通常是一种不好的做法,但是对于我最初的问题,我还有其他选择吗?

最佳答案

Q1. Which of these options is the proper way to do this?

不要在类型检查上浪费时间。

它很容易出错,因为它是基于假设的。

Q2. ... do I have any other choice?

是的,这样做。

try:
    x.the_dict_operation()
except TypeError:
    # x was not the expected type for the operation
    raise # or whatever.

在大多数情况下,这相当于“什么都不做”。

只写代码。如果“以某种方式”恶意的反社会人士使用了错误的类型,它就会像预期的那样崩溃。

关于python - 如何在 Python 中正确检查对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6905655/

相关文章:

comparison - 面向 Web 开发人员的 Windows Azure 与 Amazon EC2

javascript - 有没有人有使用 Backbone.js 和 Pylons/Pyramid 的经验?有什么 sample 要看吗?

python - 通过 Python 在 Mac 上使用蓝牙

arrays - 将数组中的所有项复制到引用类型的新数组中的函数

types - 在导出的签名中隐藏私有(private)类型

objective-c - 比较 Objective-C 中的版本号

python - AWS 与 Django

python - 如何使用 rege 从 pandas 数据框中的团队名称中提取城市名称

java - 检查 javax.lang.model.type.TypeMirror 是否为原始类型

algorithm - 比较两个英文字符串的相似性