How can I check if my python object is a number?(如何检查我的 python 对象是否为数字?)
问题描述
在 Java 中,数字类型都来自 Number,所以我会使用
In Java the numeric types all descend from Number so I would use
(x instanceof Number).
python 等价物是什么?
What is the python equivalent?
推荐答案
测试你的变量是否是 numbers.Number
:
Test if your variable is an instance of numbers.Number
:
>>> import numbers
>>> import decimal
>>> [isinstance(x, numbers.Number) for x in (0, 0.0, 0j, decimal.Decimal(0))]
[True, True, True, True]
这使用 ABCs 并且适用于所有内置在类似数字的类中,也适用于所有第三方类,如果它们是值得的(注册为 Number
ABC 的子类).
This uses ABCs and will work for all built-in number-like classes, and also for all third-party classes if they are worth their salt (registered as subclasses of the Number
ABC).
但是,在许多情况下,您不必担心手动检查类型 - Python 是 duck typed 并且混合一些兼容的类型通常是可行的,但是当某些操作没有意义时(4 - 1"
)会发出错误消息,因此很少需要手动检查.这只是一个奖金.您可以在完成模块时添加它,以避免在实现细节上纠缠他人.
However, in many cases you shouldn't worry about checking types manually - Python is duck typed and mixing somewhat compatible types usually works, yet it will barf an error message when some operation doesn't make sense (4 - "1"
), so manually checking this is rarely really needed. It's just a bonus. You can add it when finishing a module to avoid pestering others with implementation details.
这适用于从 Python 2.6 开始.在旧版本上,您几乎只能检查一些硬编码类型.
This works starting with Python 2.6. On older versions you're pretty much limited to checking for a few hardcoded types.
这篇关于如何检查我的 python 对象是否为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查我的 python 对象是否为数字?


基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01