對Python技巧——代碼效率的實際應用詳解
如果你對Python技巧——代碼效率的實際應用不是很了解的話,你就可以瀏覽以下的文章對Python技巧的實際應用有個更深入的了解,希望你在瀏覽完以下的文章你能從中學到自己想要的東西。
對象相等。您認為type(a) == type(b)和type(a) is type(b)之間的不同是什么?為什么會選擇后者?函數isinstance()與這有什么關系?
在例4.1 中我們提供了一段腳本來演示在運行時環境使用isinstance() 和 type()函數。隨后我們討論type()的使用以及怎么將這個例子移植為改用 isinstance()。運行 typechk.py, 我們會得到以下輸出:
- -69 is a number of type: int
- 9999999999999999999999 is a number of type: long
- 98.6 is a number of type: float
- (-5.2+1.9j) is a number of type: complex
- xxx is not a number at all!!
例4.1 檢查類型(typechk.py)函數displayNumType() 接受一個數值參數,Python技巧中使用內建函數type()來確認數值的類型(或不是一個數值類型)。
- #!/usr/bin/env python
- 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(9999999999999999999999L)
- displayNumType(98.6)
- displayNumType(-5.2+1.9j)
- displayNumType('xxx')
以上就是對Python技巧——代碼效率相關的內容的介紹,望你會有所收獲。
【編輯推薦】