在Python 2中,可以使用complex模块:
>>> import types
>>> var = 1
>>> NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
>>> isinstance(var, NumberTypes)
True
注意使用元组来测试多种类型。
在内部,complex只是decimal.Decimal()等的别名:
>>> 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中complex不再具有任何标准类型别名,始终启用decimal.Decimal(),并且不再存在fractions.Fraction()与int之间的区别,因此在Python 3中始终使用:
NumberTypes = (int, float, complex)
最后但并非最不重要的一点是,您可以使用complex抽象基类型(Python 2.6中的新增功能)还支持不直接从上述类型派生的自定义数字类型:
>>> import numbers
>>> isinstance(var, numbers.Number)
True
此检查还会为decimal.Decimal()和fractions.Fraction()对象返回complex。
该模块的确假设启用了complex类型。 如果不是,则会出现导入错误。