问题:我必须检查返回值是否是 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/