如何检查我的python对象是否是数字? [英] How can I check if my python object is a number?
问题描述
在 Java 中,数字类型都从 Number 下降,所以我会使用
(x instanceof Number).
python 的等价物是什么?
测试你的变量是否是 numbers.Number
:
这使用 ABCs 并将适用于所有内置 -在类似数字的类中,也适用于所有第三方类,如果它们值得的话(注册为 Number
ABC 的子类).
但是,在许多情况下,您不必担心手动检查类型 - Python 是鸭子类型 和混合一些兼容的类型通常是有效的,但是当某些操作没有意义时它会发出错误消息 (4 - "1"
),因此很少真正需要手动检查.这只是一个奖励.您可以在完成一个模块时添加它,以避免在实现细节上纠缠其他人.
这在 从 Python 2.6 开始有效.在旧版本上,您几乎只能检查一些硬编码类型.
In Java the numeric types all descend from Number so I would use
(x instanceof Number).
What is the python equivalent?
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]
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).
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.
This works starting with Python 2.6. On older versions you're pretty much limited to checking for a few hardcoded types.
这篇关于如何检查我的python对象是否是数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!