三種方法查看數字資料的類型:
[1] isinstance 可讀性更好
#! /usr/bin/env python<br />'''typechk.py'''<br />def displayNumType(num):<br /> print num, 'is',<br /> if isinstance(num, (int, long, float, complex)):<br /> print 'a number of type:', type(num).__name__<br /> else:<br /> print 'not a number at all!'<br />displayNumType(-69)<br />displayNumType(99999999999999999999L)<br />displayNumType(99999999999999999999)<br />displayNumType(98.6)<br />displayNumType(-5.2+1.9j)<br />displayNumType('aaa')<br />#######<br /># output<br />#######<br />-69 is a number of type: int<br />99999999999999999999 is a number of type: long<br />99999999999999999999 is a number of type: long<br />98.6 is a number of type: float<br />(-5.2+1.9j) is a number of type: complex<br />aaa is not a number at all!<br />
[2] 調用兩次type
#! /usr/bin/env<br />python<br />'''typechk.py'''<br />def displayNumType(num):<br /> print num, 'is',<br /> if type(num)==type(0):<br /> print 'an integer'<br /> elif type(num)==type(0L):<br /> print 'a long'<br /> elif type(num)==type(0.0):<br /> print 'a float'<br /> elif type(num)==type(0+0j):<br /> print 'a complex number'<br /> else:<br /> print 'not a number at all!'<br />displayNumType(-69)<br />displayNumType(99999999999999999999L)<br />displayNumType(99999999999999999999)<br />displayNumType(98.6)<br />displayNumType(-5.2+1.9j)<br />displayNumType('aaa')<br />#######<br /># output<br />#######<br />-69 is an integer<br />99999999999999999999 is a long<br />99999999999999999999 is a long<br />98.6 is a float<br />(-5.2+1.9j) is a complex number<br />aaa is not a number at all!<br />
[3] import types
#! /usr/bin/env<br />python<br />import types<br />'''typechk.py'''<br />def displayNumType(num):<br /> print num, 'is',<br /> if type(num)==types.IntType:<br /> print 'an integer'<br /> elif type(num)==types.LongType:<br /> print 'a long'<br /> elif type(num)==types.FloatType:<br /> print 'a float'<br /> elif type(num)==types.ComplexType:<br /> print 'a complex number'<br /> else:<br /> print 'not a number at all!',</p><p> print 'but, it is',<br /> if type(num)==types.StringType:<br /> print 'a string'</p><p>displayNumType(-69)<br />displayNumType(99999999999999999999L)<br />displayNumType(99999999999999999999)<br />displayNumType(98.6)<br />displayNumType(-5.2+1.9j)<br />displayNumType('aaa')<br />#######<br /># output<br />#######<br />-69 is an integer<br />99999999999999999999 is a long<br />99999999999999999999 is a long<br />98.6 is a float<br />(-5.2+1.9j) is a complex number<br />aaa is not a number at all! but, it is a string<br />