| 導航:起始頁 > Dive Into Python > 自省的威力 > 使用 type、str、dir 和其它內置函數 | << >> | ||||
深入 Python :Dive Into Python 中文版Python 從新手到專家 [Dip_5.4b_CPyUG_Release] |
|||||
Python 有小部分相當有用的內置函數。除這些函數之外,其它所有的函數都被分到了各個模塊中。其實這是一個非常明智的設計策略,避免了核心語言變得像其它腳本語言一樣臃腫 (咳 咳,Visual Basic)。
type 函數返回任意對象的數據類型。在 types 模塊中列出了可能的數據類型。這對于處理多種數據類型的幫助者函數 [1] 非常有用。
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'
info 函數的核心是強大的 dir 函數。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']
| li 是一個列表,所以 dir(li) 返回一個包含所有列表方法的列表。注意返回的列表只包含了字符串形式的方法名稱,而不是方法對象本身。 | |
| d 是一個字典,所以 dir(d) 返回字典方法的名稱列表。其中至少有一個方法,keys,看起來還是挺熟悉的。 | |
| 這里就是真正變得有趣的地方。odbchelper 是一個模塊,所以 dir(odbchelper) 返回模塊中定義的所有部件的列表,包括內置的屬性,例如 __name__、__doc__,以及其它你所定義的屬性和方法。在這個例子中,odbchelper 只有一個用戶定義的方法,就是在第 2 章中論述的 buildConnectionString 函數。 |
最后是 callable 函數,它接收任何對象作為參數,如果參數對象是可調用的,返回 True;否則返回 False。可調用對象包括函數、類方法,甚至類自身 (下一章將更多的關注類)。
>>> 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)
| string 模塊中的函數現在已經不贊成使用了 (盡管很多人現在仍然還在使用 join 函數),但是在這個模塊中包含了許多有用的變量,例如 string.punctuation,這個字符串包含了所有標準的標點符號字符。 | |
| string.join 是一個用于連接字符串列表的函數。 | |
| string.punctuation 是不可調用的對象;它是一個字符串。(字符串確有可調用的方法,但是字符串本身不是可調用的。) | |
| string.join 是可調用的;這個函數可以接受兩個參數。 | |
| 任何可調用的對象都有 doc string。通過將 callable 函數作用于一個對象的每個屬性,可以確定哪些屬性 (方法、函數、類) 是你要關注的,哪些屬性 (常量等等) 是你可以忽略、之前不需要知道的。 |
type、str、dir 和其它的 Python 內置函數都歸組到了 __builtin__ (前后分別是雙下劃線) 這個特殊的模塊中。如果有幫助的話,你可以認為 Python 在啟動時自動執行了 from __builtin__ import *,此語句將所有的 “內置” 函數導入該命名空間,所以在這個命名空間中可以直接使用這些內置函數。
像這樣考慮的好處是,你是可以獲取 __builtin__ 模塊信息的,并以組的形式訪問所有的內置函數和屬性。猜到什么了嗎,現在我們的 Python 有一個稱為 info 的函數。自己嘗試一下,略看一下結果列表。后面我們將深入到一些更重要的函數。(一些內置的錯誤類,比如 AttributeError,應該看上去已經很熟悉了。)
>>> 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 不同于此,它很大程度上是自文檔化的。 | |
[1] 幫助者函數,原文是 helper function,也就是我們在前文所看到的諸如 odbchelper、apihelper 這樣的函數。――譯注
<< 使用可選參數和命名參數 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
通過 getattr 獲取對象引用 >> |