標籤:python 最佳化 對象
# -*- coding: utf-8 -*-## 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!!'# # # #減少函數調用的次數# #代碼在進行判斷時使用了兩次type()函數,我們使用types模組中的變數代替之# import types# # if type(num) == types.IntType:# pass# # #對象身份比較優於對象值比較# #值比較:# if type(num) == type(0):# pass# #對象身份比較:# if type(num) is types.IntType:# pass# # #減少查詢次數# #import types# from types import IntType# if type(num) is IntType:# pass# # #慣例風格可讀性的考慮:使用isinstance()# # # 最終代碼def displayNumType(num): print num ,'is', #isinstance同時判斷多個種類的用法 #如果是這四個其中之一 if isinstance(num,(int, long, float, complex)): #返回這個type的名字 print 'a number of type:', type(num).__name__ else: print 'not a number at all!!'displayNumType(-69)displayNumType(9999999999999999999999999L)displayNumType(98.6)displayNumType(-5.2+1.9j)displayNumType('xxx')
Python 代碼最佳化基礎——判斷物件類型