標籤:python
第一版舉例:
def displayNumType(num): print num,"is", if type(num)==type(0): print 'an interger' 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!!'
最終版舉例:
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!!'
最佳化思路:
1、減少函數調用的次數
在第一版代碼中,每次判斷會調用兩次type()。
import typesif type(num)==types.IntType...
2、對象值比較 VS 對象身份比較
type(0),type(42)等都是同一個對象“<type 'Int'>”,沒有必要進行值得比較。因為每一個類型只有一個類型對象。
if type(num) is types.IntType... ##or type(0)
3、減少查詢次數
為了得到整數的物件類型,解譯器不得不首先尋找types這個模組的名字,然後在該模組的字典中尋找IntType。
通過使用from-import,可以減少一次查詢。
from types import IntTypeif type(num) is IntType
4、慣例和代碼風格
isinstance()函數讓if語句更方便,並具有更好的可讀性。
if isinstance(num,int)...
摘選自《python核心編程(第二版)》第四章P68
python代碼最佳化案例分析