對(duì)Python技巧——代碼效率的實(shí)際應(yīng)用詳解
如果你對(duì)Python技巧——代碼效率的實(shí)際應(yīng)用不是很了解的話,你就可以瀏覽以下的文章對(duì)Python技巧的實(shí)際應(yīng)用有個(gè)更深入的了解,希望你在瀏覽完以下的文章你能從中學(xué)到自己想要的東西。
對(duì)象相等。您認(rèn)為type(a) == type(b)和type(a) is type(b)之間的不同是什么?為什么會(huì)選擇后者?函數(shù)isinstance()與這有什么關(guān)系?
在例4.1 中我們提供了一段腳本來(lái)演示在運(yùn)行時(shí)環(huán)境使用isinstance() 和 type()函數(shù)。隨后我們討論type()的使用以及怎么將這個(gè)例子移植為改用 isinstance()。運(yùn)行 typechk.py, 我們會(huì)得到以下輸出:
- -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)函數(shù)displayNumType() 接受一個(gè)數(shù)值參數(shù),Python技巧中使用內(nèi)建函數(shù)type()來(lái)確認(rèn)數(shù)值的類型(或不是一個(gè)數(shù)值類型)。
- #!/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')
以上就是對(duì)Python技巧——代碼效率相關(guān)的內(nèi)容的介紹,望你會(huì)有所收獲。
【編輯推薦】