python - 如何正确判断类型?

标签 python

这可能已经被问过一百次了,但你是自己成功的产物!

在 Python 中,我在其他人的代码中看到了这一点

if type(number) != type(1):

这样做有什么好的理由,不应该

if type(number) != int

是更好的方法吗?

这是历史事件吗?

最佳答案

这两种方法都不是正确的。

正确的方法是使用isinstance():

if not isinstance(number, int):

这确保子类也不允许。

极其罕见的情况下,您必须绝对只禁止 int 并允许子类,您使用 type() 而不是 ;类型是单例:

if type(number) is not int:

更pythonic的是使用ask forgovernance而不是permission;将该值视为整数,直到证明不是这样(例如通过异常)。

关于python - 如何正确判断类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25955833/

相关文章:

python - 权限不足 : plone. app.multilingual [1.x] - 翻译原型(prototype)内容

python - 如何制作一个虚拟列来确定列单元格值是否重复?

python - 使用 PyQt 闪烁小部件

python - 使用 matshow 时 matplotlib 中的自定义颜色

python - 使用 Numpy(坐标变换)计算长表达式?

python - 计算列表列表中列表的出现次数

python - 将 sys.stdout 重定向到特定的 Jupyter Notebook 单元格

python - 如何使用 datetime.time 在 Python 中绘图

python - 计算质数

python - 是否可以使用 NetworkX 在给定图像上绘制图形?