在 Python 2 中,您可以使用 types module:
>>> import types
>>> var = 1
>>> NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
>>> isinstance(var, NumberTypes)
True
注意使用元组来测试多种类型。
在后台,IntType 只是int 的别名,等等:
>>> isinstance(var, (int, long, float, complex))
True
complex 类型要求您的 python 编译时支持复数;如果您想对此进行防范,请使用 try/except 块:
>>> try:
... NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
... except AttributeError:
... # No support for complex numbers compiled
... NumberTypes = (types.IntType, types.LongType, types.FloatType)
...
或者如果你直接使用类型:
>>> try:
... NumberTypes = (int, long, float, complex)
... except NameError:
... # No support for complex numbers compiled
... NumberTypes = (int, long, float)
...
在 Python 3 中,types 不再有任何标准类型别名,complex 始终处于启用状态,并且不再存在 long 与 int 的区别,因此在 Python 3 中始终使用:
NumberTypes = (int, float, complex)
最后但同样重要的是,您可以使用numbers.Numbers abstract base type(Python 2.6 中的新功能)来支持不直接从上述类型派生的自定义数字类型:
>>> import numbers
>>> isinstance(var, numbers.Number)
True
此检查还为 decimal.Decimal() 和 fractions.Fraction() 对象返回 True。
该模块确实假设启用了complex 类型;如果不是,您将收到导入错误。