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 对象是否为数字?


- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01