可以使用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
類型要求你的蟒蛇與複雜的數字支持編譯;如果你想守護這個使用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)
...
最後但並非最不重要的,你可以使用numbers.Numbers
abstract base type(新中Python 2.6中),也支持自定義數值類型不直接從上述類型推導:
>>> import numbers
>>> isinstance(var, numbers.Number)
True
這個模塊確實讓該complex
類型啓用的假設;如果不是,你會得到一個導入錯誤。
如果你願意使用numpy,'numpy.isfinite'應該可以做到。 –