如何检查我的 python 对象是否为数字?

2022-01-17 00:00:00 python numbers types

问题描述

在 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.

相关文章