您的位置:首页 > 编程语言 > Python开发

python中的type()和isinstance()

2017-07-08 15:57 429 查看

type()和instance()

python核心编程第二版,书中第四章关于type()和isinstance()的介绍非常有趣,摘录如下。

一个关于判断对象为那种number类型的函数:

def jundgle(num):
print(num, end='')
if type(num) == type(0):
print('is an integer')
if type(num) == type(0.0):
print('is a float')
if type(num) == type(0+0j):
print('is a complex number')


在这段代码中每一个if语句中都调用了两次type()函数,如果能减少调用type()函数的次数那么程序的性能可以提升。如何减少type()函数的次数呢?可以直接使用type对象而不是用type()函数每次都计算出自己给出的数字比如type(0)和type(0.0)…额有点小尴尬,这段代码并不能在python3上运行python3types的官方文档并没有出现types.IntType等。

import types
def jundgle(num):
if type(num) == types.IntType:
print('is an integer')
if type(num) == types.FloatType:
print('is a float')
if type(num) == types.ComplexType:
print('is a complex number')


在这里虽然说减少了type()函数的调用但是if语句也是很多的能不能只用一条if语句就能完成判断呢?这时候就需要isinstanc()函数了。

def jundgle(num):
print(num, end='')
if isinstance(num, (int, float, complex)):
print('is a number of type:', type(num).__name__)
else:
print('not a number at all.')


是不是更简单一点了?这篇博客只是写着玩而已,思路啥的基本上都是书上的,只是看书看的没意思就敲了出来。希望下午四点的LPL和LMS的比赛,LPL赛出自己的风格。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python