| 導航:起始頁 > Dive Into Python > 自省的威力 | << >> | ||||
深入 Python :Dive Into Python 中文版Python 從新手到專家 [Dip_5.4b_CPyUG_Release] |
|||||
本章論述了 Python 眾多強大功能之一:自省。正如你所知道的,Python 中萬物皆對象,自省是指代碼可以查看內存中以對象形式存在的其它模塊和函數,獲取它們的信息,并對它們進行操作。用這種方法,你可以定義沒有名稱的函數,不按函數聲明的參數順序調用函數,甚至引用事先并不知道名稱的函數。
下面是一個完整可運行的 Python 程序。大概看一下這段程序,你應該可以理解不少了。用數字標出的行闡述了 第 2 章 第一個 Python 程序 中涉及的一些概念。如果剩下來的代碼看起來有點奇怪,不用擔心,通過閱讀本章你將會理解所有這些。
如果您還沒有下載本書附帶的樣例程序, 可以 下載本程序和其他樣例程序。
def info(object, spacing=10, collapse=1):![]()
![]()
"""Print methods and doc strings. Takes module, class, list, dictionary, or string.""" methodList = [method for method in dir(object) if callable(getattr(object, method))] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print "\n".join(["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList]) if __name__ == "__main__":
![]()
print info.__doc__
| 該模塊有一個聲明為 info 的函數。根據它的函數聲明可知,它有三個參數: object、spacing 和 collapse。實際上后面兩個參數都是可選參數,關于這點你很快就會看到。 | |
| info 函數有一個多行的 doc string,簡要地描述了函數的功能。注意這里并沒有提到返回值;單獨使用這個函數只是為了這個函數產生的效果,并不是為了它的返回值。 | |
| 函數內的代碼是縮進形式的。 | |
| if __name__ 技巧允許這個程序在自己獨立運行時做些有用的事情,同時又不妨礙作為其它程序的模塊使用。在這個例子中,程序只是簡單地打印出 info 函數的 doc string。 | |
| if 語句使用 == 進行比較,而且不需要括號。 |
info 函數的設計意圖是提供給工作在 Python IDE 中的開發人員使用,它可以接受任何含有函數或者方法的對象 (比如模塊,含有函數,又比如list,含有方法) 作為參數,并打印出對象的所有函數和它們的 doc string。
>>> from apihelper import info >>> li = [] >>> info(li) append L.append(object) -- append object to end count L.count(value) -> integer -- return number of occurrences of value extend L.extend(list) -- extend list by appending list elements index L.index(value) -> integer -- return index of first occurrence of value insert L.insert(index, object) -- insert object before index pop L.pop([index]) -> item -- remove and return item at index (default last) remove L.remove(value) -- remove first occurrence of value reverse L.reverse() -- reverse *IN PLACE* sort L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1
缺省地,程序輸出進行了格式化處理,以使其易于閱讀。多行 doc string 被合并到單行中,要改變這個選項需要指定 collapse 參數的值為 0。如果函數名稱長于10個字符,你可以將 spacing 參數的值指定為更大的值以使輸出更容易閱讀。
>>> import odbchelper >>> info(odbchelper) buildConnectionString Build a connection string from a dictionary Returns string. >>> info(odbchelper, 30) buildConnectionString Build a connection string from a dictionary Returns string. >>> info(odbchelper, 30, 0) buildConnectionString Build a connection string from a dictionary Returns string.
<< 小結 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
使用可選參數和命名參數 >> |