Python 代碼最佳化基礎——判斷物件類型

來源:互聯網
上載者:User

標籤: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 代碼最佳化基礎——判斷物件類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.