在Python 2中,您可以使用
types模块:
>>> 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始终启用,并且不再存在
longvs
int差异,因此在Python
3中始终使用:
NumberTypes = (int, float, complex)
最后但并非最不重要的一点是,您可以使用
numbers.Numbers抽象基类型(Python
2.6中的新增功能)还支持不直接从上述类型派生的自定义数字类型:
>>> import numbers>>> isinstance(var, numbers.Number)True
此检查也返回
True了
decimal.Decimal()和
fractions.Fraction()对象。
该模块确实假定
complex已启用该类型。如果不是,则会出现导入错误。



