Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
528
|
16 章 測試、除錯和最佳化
如何透過這些類別和它們的方法內省 callable 的特徵式,詳細的資訊和範
例請參閱 PEP 362
https://www.python.org/dev/peps/pep-0362/
)。
使用 inspect 的一個範例
假設你程式中的某個地方執行了像這樣的一個述句:
x.f()
並且非預期地接受到一個
AttributeError
告知你物件
x
沒有名為
f
的屬
性。這代表物件
x
並不如你所預期,所以你想要找出有關
x
的更多資訊,
以判斷
x
為何會變成那樣,以及你應該怎麼處理它。將該述句改為:
try: x.f()
except AttributeError:
import sys, inspect
print('x is type {}, ({!r})'.format(type(x), x), file=sys.stderr)
print("x's methods are:", file=sys.stderr, end='')
for n, v in inspect.getmembers(x, callable):
print(n, file=sys.stderr, end='')
print(file=sys.stderr)
raise
這個範例使用
sys.stderr
(涵蓋於表 7-3),因為它顯示的是與錯誤有關的
資訊,而非程式結果。模組
inspect
的函式
getmembers
會取得
x
上所有可
用方法的名稱以顯示它們。如果你經常會需要這種診斷用的功能性,就將 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819