# 4.3.?使用 `type`、`str`、`dir` 和其它內置函數
* 4.3.1\. type 函數
* 4.3.2\. str 函數
* 4.3.3\. 內置函數
Python 有小部分相當有用的內置函數。除這些函數之外,其它所有的函數都被分到了各個模塊中。其實這是一個非常明智的設計策略,避免了核心語言變得像其它腳本語言一樣臃腫 (咳 咳,Visual Basic)。
## 4.3.1.?`type` 函數
`type` 函數返回任意對象的數據類型。在 `types` 模塊中列出了可能的數據類型。這對于處理多種數據類型的幫助者函數 \[1\] 非常有用。
## 例?4.5.?`type` 介紹
```
>>> type(1)
<type 'int'>
>>> li = []
>>> type(li)
<type 'list'>
>>> import odbchelper
>>> type(odbchelper)
<type 'module'>
>>> import types
>>> type(odbchelper) == types.ModuleType
True
```
| | |
| --- | --- |
| \[1\] | `type` 可以接收任何東西作為參數――我的意思是任何東西――并返回它的數據類型。整型、字符串、列表、字典、元組、函數、類、模塊,甚至類型對象都可以作為參數被 `type` 函數接受。 |
| \[2\] | `type` 可以接收變量作為參數,并返回它的數據類型。 |
| \[3\] | `type` 還可以作用于模塊。 |
| \[4\] | 你可以使用 `types` 模塊中的常量來進行對象類型的比較。這就是 `info` 函數所做的,很快你就會看到。 |
## 4.3.2.?`str` 函數
`str` 將數據強制轉換為字符串。每種數據類型都可以強制轉換為字符串。
## 例?4.6.?`str` 介紹
```
>>> str(1)
'1'
>>> horsemen = ['war', 'pestilence', 'famine']
>>> horsemen
['war', 'pestilence', 'famine']
>>> horsemen.append('Powerbuilder')
>>> str(horsemen)
"['war', 'pestilence', 'famine', 'Powerbuilder']"
>>> str(odbchelper)
"<module 'odbchelper' from 'c:\\docbook\\dip\\py\\odbchelper.py'>"
>>> str(None)
'None'
```
| | |
| --- | --- |
| \[1\] | 對于簡單的數據類型比如整型,你可以預料到 `str` 的正常工作,因為幾乎每種語言都有一個將整型轉化為字符串的函數。 |
| \[2\] | 然而 `str` 可以作用于任何數據類型的任何對象。這里它作用于一個零碎構建的列表。 |
| \[3\] | `str` 還允許作用于模塊。注意模塊的字符串形式表示包含了模塊在磁盤上的路徑名,所以你的顯示結果將會有所不同。 |
| \[4\] | `str` 的一個細小但重要的行為是它可以作用于 `None`,`None` 是 Python 的 null 值。這個調用返回字符串 `'None'`。你將會使用這一點來改進你的 `info` 函數,這一點你很快就會看到。 |
`info` 函數的核心是強大的 `dir` 函數。`dir` 函數返回任意對象的屬性和方法列表,包括模塊對象、函數對象、字符串對象、列表對象、字典對象 …… 相當多的東西。
## 例?4.7.?`dir` 介紹
```
>>> li = []
>>> dir(li)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>> d = {}
>>> dir(d)
['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'setdefault', 'update', 'values']
>>> import odbchelper
>>> dir(odbchelper)
['__builtins__', '__doc__', '__file__', '__name__', 'buildConnectionString']
```
| | |
| --- | --- |
| \[1\] | `li` 是一個列表,所以 ``dir`(`li`)` 返回一個包含所有列表方法的列表。注意返回的列表只包含了字符串形式的方法名稱,而不是方法對象本身。 |
| \[2\] | `d` 是一個字典,所以 ``dir`(`d`)` 返回字典方法的名稱列表。其中至少有一個方法,[`keys`](../native_data_types/mapping_lists.html#odbchelper.items "例?3.25.?keys, values 和 items 函數"),看起來還是挺熟悉的。 |
| \[3\] | 這里就是真正變得有趣的地方。`odbchelper` 是一個模塊,所以 ``dir`(`odbchelper`)` 返回模塊中定義的所有部件的列表,包括內置的屬性,例如 [`__name__`](../getting_to_know_python/testing_modules.html#odbchelper.ifnametrick)、[`__doc__`](../getting_to_know_python/everything_is_an_object.html#odbchelper.import "例?2.3.?訪問 buildConnectionString 函數的 doc string"),以及其它你所定義的屬性和方法。在這個例子中,`odbchelper` 只有一個用戶定義的方法,就是在[第 2 章](../getting_to_know_python/index.html)中論述的 `buildConnectionString` 函數。 |
最后是 `callable` 函數,它接收任何對象作為參數,如果參數對象是可調用的,返回 `True`;否則返回 `False`。可調用對象包括函數、類方法,甚至類自身 (下一章將更多的關注類)。
## 例?4.8.?`callable` 介紹
```
>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.join
<function join at 00C55A7C>
>>> callable(string.punctuation)
False
>>> callable(string.join)
True
>>> print string.join.__doc__
join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
```
| | |
| --- | --- |
| \[1\] | `string` 模塊中的函數現在已經不贊成使用了 (盡管很多人現在仍然還在使用 `join` 函數),但是在這個模塊中包含了許多有用的變量,例如 `string.punctuation`,這個字符串包含了所有標準的標點符號字符。 |
| \[2\] | [`string.join`](../native_data_types/joining_lists.html "3.7.?連接 list 與分割字符串") 是一個用于連接字符串列表的函數。 |
| \[3\] | `string.punctuation` 是不可調用的對象;它是一個字符串。(字符串確有可調用的方法,但是字符串本身不是可調用的。) |
| \[4\] | `string.join` 是可調用的;這個函數可以接受兩個參數。 |
| \[5\] | 任何可調用的對象都有 `doc string`。通過將 `callable` 函數作用于一個對象的每個屬性,可以確定哪些屬性 (方法、函數、類) 是你要關注的,哪些屬性 (常量等等) 是你可以忽略、之前不需要知道的。 |
## 4.3.3.?內置函數
`type`、`str`、`dir` 和其它的 Python 內置函數都歸組到了 `__builtin__` (前后分別是雙下劃線) 這個特殊的模塊中。如果有幫助的話,你可以認為 Python 在啟動時自動執行了 `from __builtin__ import *`,此語句將所有的 “內置” 函數導入該命名空間,所以在這個命名空間中可以直接使用這些內置函數。
像這樣考慮的好處是,你是可以獲取 `__builtin__` 模塊信息的,并以組的形式訪問所有的內置函數和屬性。猜到什么了嗎,現在我們的 Python 有一個稱為 `info` 的函數。自己嘗試一下,略看一下結果列表。后面我們將深入到一些更重要的函數。(一些內置的錯誤類,比如 [`AttributeError`](../native_data_types/tuples.html#odbchelper.tuplemethods "例?3.16.?Tuple 沒有方法"),應該看上去已經很熟悉了。)
## 例?4.9.?內置屬性和內置函數
```
>>> from apihelper import info
>>> import __builtin__
>>> info(__builtin__, 20)
ArithmeticError Base class for arithmetic errors.
AssertionError Assertion failed.
AttributeError Attribute not found.
EOFError Read beyond end of file.
EnvironmentError Base class for I/O related errors.
Exception Common base class for all exceptions.
FloatingPointError Floating point operation failed.
IOError I/O operation failed.
[...snip...]
```
> 注意
> Python 提供了很多出色的參考手冊,你應該好好地精讀一下所有 Python 提供的必備模塊。對于其它大部分語言,你會發現自己要常常回頭參考手冊或者 man 頁來提醒自己如何使用這些模塊,但是 Python 不同于此,它很大程度上是自文檔化的。
## 進一步閱讀
* _Python Library Reference_ 對[所有的內置函數](http://www.python.org/doc/current/lib/built-in-funcs.html)和[所有的內置異常](http://www.python.org/doc/current/lib/module-exceptions.html)都進行了文檔化。
## Footnotes
\[1\] 幫助者函數,原文是 helper function,也就是我們在前文所看到的諸如 `odbchelper`、`apihelper` 這樣的函數。――譯注
- 版權信息
- 第?1?章?安裝 Python
- 1.1.?哪一種 Python 適合您?
- 1.2.?Windows 上的 Python
- 1.3.?Mac OS X 上的 Python
- 1.4.?Mac OS 9 上的 Python
- 1.5.?RedHat Linux 上的 Python
- 1.6.?Debian GNU/Linux 上的 Python
- 1.7.?從源代碼安裝 Python
- 1.8.?使用 Python 的交互 Shell
- 1.9.?小結
- 第?2?章?第一個 Python 程序
- 2.1.?概覽
- 2.2.?函數聲明
- 2.3.?文檔化函數
- 2.4.?萬物皆對象
- 2.5.?代碼縮進
- 2.6.?測試模塊
- 第?3?章?內置數據類型
- 3.1.?Dictionary 介紹
- 3.2.?List 介紹
- 3.3.?Tuple 介紹
- 3.4.?變量聲明
- 3.5.?格式化字符串
- 3.6.?映射 list
- 3.7.?連接 list 與分割字符串
- 3.8.?小結
- 第?4?章?自省的威力
- 4.1.?概覽
- 4.2.?使用可選參數和命名參數
- 4.3.?使用 type、str、dir 和其它內置函數
- 4.4.?通過 getattr 獲取對象引用
- 4.5.?過濾列表
- 4.6.?and 和 or 的特殊性質
- 4.7.?使用 lambda 函數
- 4.8.?全部放在一起
- 4.9.?小結
- 第?5?章?對象和面向對象
- 5.1.?概覽
- 5.2.?使用 from _module_ import 導入模塊
- 5.3.?類的定義
- 5.4.?類的實例化
- 5.5.?探索 UserDict:一個封裝類
- 5.6.?專用類方法
- 5.7.?高級專用類方法
- 5.8.?類屬性介紹
- 5.9.?私有函數
- 5.10.?小結
- 第?6?章?異常和文件處理
- 6.1.?異常處理
- 6.2.?與文件對象共事
- 6.3.?for 循環
- 6.4.?使用 `sys.modules`
- 6.5.?與目錄共事
- 6.6.?全部放在一起
- 6.7.?小結
- 第?7?章?正則表達式
- 7.1.?概覽
- 7.2.?個案研究:街道地址
- 7.3.?個案研究:羅馬字母
- 7.4.?使用 {n,m} 語法
- 7.5.?松散正則表達式
- 7.6.?個案研究:解析電話號碼
- 7.7.?小結
- 第?8?章?HTML 處理
- 8.1.?概覽
- 8.2.?sgmllib.py 介紹
- 8.3.?從 HTML 文檔中提取數據
- 8.4.?BaseHTMLProcessor.py 介紹
- 8.5.?locals 和 globals
- 8.6.?基于 dictionary 的字符串格式化
- 8.7.?給屬性值加引號
- 8.8.?dialect.py 介紹
- 8.9.?全部放在一起
- 8.10.?小結
- 第?9?章?XML 處理
- 9.1.?概覽
- 9.2.?包
- 9.3.?XML 解析
- 9.4.?Unicode
- 9.5.?搜索元素
- 9.6.?訪問元素屬性
- 9.7.?Segue [9]
- 第?10?章?腳本和流
- 10.1.?抽象輸入源
- 10.2.?標準輸入、輸出和錯誤
- 10.3.?查詢緩沖節點
- 10.4.?查找節點的直接子節點
- 10.5.?根據節點類型創建不同的處理器
- 10.6.?處理命令行參數
- 10.7.?全部放在一起
- 10.8.?小結
- 第?11?章?HTTP Web 服務
- 11.1.?概覽
- 11.2.?避免通過 HTTP 重復地獲取數據
- 11.3.?HTTP 的特性
- 11.4.?調試 HTTP web 服務
- 11.5.?設置 User-Agent
- 11.6.?處理 Last-Modified 和 ETag
- 11.7.?處理重定向
- 11.8.?處理壓縮數據
- 11.9.?全部放在一起
- 11.10.?小結
- 第?12?章?SOAP Web 服務
- 12.1.?概覽
- 12.2.?安裝 SOAP 庫
- 12.3.?步入 SOAP
- 12.4.? SOAP 網絡服務查錯
- 12.5.?WSDL 介紹
- 12.6.?以 WSDL 進行 SOAP 內省
- 12.7.?搜索 Google
- 12.8.? SOAP 網絡服務故障排除
- 12.9.?小結
- 第?13?章?單元測試
- 13.1.?羅馬數字程序介紹 II
- 13.2.?深入
- 13.3.?romantest.py 介紹
- 13.4.?正面測試 (Testing for success)
- 13.5.?負面測試 (Testing for failure)
- 13.6.?完備性檢測 (Testing for sanity)
- 第?14?章?測試優先編程
- 14.1.?roman.py, 第 1 階段
- 14.2.?roman.py, 第 2 階段
- 14.3.?roman.py, 第 3 階段
- 14.4.?roman.py, 第 4 階段
- 14.5.?roman.py, 第 5 階段
- 第?15?章?重構
- 15.1.?處理 bugs
- 15.2.?應對需求變化
- 15.3.?重構
- 15.4.?后記
- 15.5.?小結
- 第?16?章?函數編程
- 16.1.?概覽
- 16.2.?找到路徑
- 16.3.?重識列表過濾
- 16.4.?重識列表映射
- 16.5.?數據中心思想編程
- 16.6.?動態導入模塊
- 16.7.?全部放在一起
- 16.8.?小結
- 第?17?章?動態函數
- 17.1.?概覽
- 17.2.?plural.py, 第 1 階段
- 17.3.?plural.py, 第 2 階段
- 17.4.?plural.py, 第 3 階段
- 17.5.?plural.py, 第 4 階段
- 17.6.?plural.py, 第 5 階段
- 17.7.?plural.py, 第 6 階段
- 17.8.?小結
- 第?18?章?性能優化
- 18.1.?概覽
- 18.2.?使用 timeit 模塊
- 18.3.?優化正則表達式
- 18.4.?優化字典查找
- 18.5.?優化列表操作
- 18.6.?優化字符串操作
- 18.7.?小結
- 附錄?A.?進一步閱讀
- 附錄?B.?五分鐘回顧
- 附錄?C.?技巧和竅門
- 附錄?D.?示例清單
- 附錄?E.?修訂歷史
- 附錄?F.?關于本書
- 附錄 G. GNU Free Documentation License
- G.0. Preamble
- G.1.?Applicability and definitions
- G.2.?Verbatim copying
- G.3.?Copying in quantity
- G.4.?Modifications
- G.5.?Combining documents
- G.6.?Collections of documents
- G.7.?Aggregation with independent works
- G.8.?Translation
- G.9.?Termination
- G.10.?Future revisions of this license
- G.11.?How to use this License for your documents
- 附錄 H. GNU 自由文檔協議
- H.0. 序
- H.1.?適用范圍和定義
- H.2.?原樣復制
- H.3.?大量復制
- H.4.?修改
- H.5.?合并文檔
- H.6.?文檔合集
- H.7.?獨立著作聚集
- H.8.?翻譯
- H.9.?終止協議
- H.10.?協議將來的修訂
- H.11.?如何為你的文檔使用本協議
- 附錄 I. Python license
- I.A. History of the software
- I.B.?Terms and conditions for accessing or otherwise using Python
- 附錄 J. Python 協議
- J.0. 關于譯文的聲明
- J.A.?軟件的歷史
- J.B.?使用 Python 的條款和條件