Python核心编程——第四章Python对象
2010-08-31 10:37
405 查看
三种方法查看数字数据的类型:
[1] isinstance 可读性更好
[2] 调用两次type
[3] import types
[1] isinstance 可读性更好
#! /usr/bin/env python '''typechk.py''' def displayNumType(num): print num, 'is', if isinstance(num, (int, long, float, complex)): print 'a number of type:', type(num).__name__ else: print 'not a number at all!' displayNumType(-69) displayNumType(99999999999999999999L) displayNumType(99999999999999999999) displayNumType(98.6) displayNumType(-5.2+1.9j) displayNumType('aaa') ####### # output ####### -69 is a number of type: int 99999999999999999999 is a number of type: long 99999999999999999999 is a number of type: long 98.6 is a number of type: float (-5.2+1.9j) is a number of type: complex aaa is not a number at all!
[2] 调用两次type
#! /usr/bin/env python '''typechk.py''' def displayNumType(num): print num, 'is', if type(num)==type(0): print 'an integer' elif type(num)==type(0L): print 'a long' elif type(num)==type(0.0): print 'a float' elif type(num)==type(0+0j): print 'a complex number' else: print 'not a number at all!' displayNumType(-69) displayNumType(99999999999999999999L) displayNumType(99999999999999999999) displayNumType(98.6) displayNumType(-5.2+1.9j) displayNumType('aaa') ####### # output ####### -69 is an integer 99999999999999999999 is a long 99999999999999999999 is a long 98.6 is a float (-5.2+1.9j) is a complex number aaa is not a number at all!
[3] import types
#! /usr/bin/env python import types '''typechk.py''' def displayNumType(num): print num, 'is', if type(num)==types.IntType: print 'an integer' elif type(num)==types.LongType: print 'a long' elif type(num)==types.FloatType: print 'a float' elif type(num)==types.ComplexType: print 'a complex number' else: print 'not a number at all!', print 'but, it is', if type(num)==types.StringType: print 'a string' displayNumType(-69) displayNumType(99999999999999999999L) displayNumType(99999999999999999999) displayNumType(98.6) displayNumType(-5.2+1.9j) displayNumType('aaa') ####### # output ####### -69 is an integer 99999999999999999999 is a long 99999999999999999999 is a long 98.6 is a float (-5.2+1.9j) is a complex number aaa is not a number at all! but, it is a string
相关文章推荐
- 《Python核心编程》第四章:Python 对象
- 《Python核心编程》第二版--第四章 Python对象
- 《Python核心编程》 第四章 Python对象- 课后习题
- python核心编程——python对象
- 第四章 Python对象练习题--自我总结
- 《Python 学习手册4th》 第四章 介绍Python对象类型
- python核心编程(四)— python对象
- Python中的List对象(Python 源码剖析第四章)
- python核心编程——python对象
- 《Python核心编程》(第二版) 第4章 Python对象
- 《Python核心编程》笔记 Python对象
- python学习手册(第四章:介绍python对象类型)
- Python学习笔记《Python核心编程》第4章Python对象
- 第四章 Python 对象
- 第四章、介绍Python对象类型
- 《Python核心编程》读书笔记之Python对象浅拷贝和深拷贝
- 第四章Python对象
- 《Python CookBook2》 第四章 Python技巧 对象拷贝 && 通过列表推导构建列表
- 【Python学习】python学习手册--第四章 Python对象类型
- 【python学习】多线程 与 面向对象 结合的一个经典例子