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 技術手冊 第三版
212
|
6 章 模組
模組主體中頂層述句的循序執行(sequential execution),藉此對事情發生
的順序有更好的控制。通常,移除循環相依性會比確保帶有循環相依性的
程式碼會以不出錯的順序執行還要容易。
sys.modules 中的條目(Entries
__import__
永遠都不會將模組物件以外的東西繫結為
sys.modules
中的
值。然而,如果
__import__
sys.modules
中找到已經存在的一個條目
entry),它就會回傳那個值,不管其型別為何。
import
from
述句在
內部都仰賴
__import__
,所以它們最後也可能用到不是模組的物件。這讓
你能設定類別實體作為
sys.modules
中的條目,以利用
__getattr__
__
setattr__
這類特殊方法的功能,如前面「一般用途的特殊方法」中所涵
蓋的。這個很少會用到的進階技巧能讓你匯入類模組的物件(module-like
objects),而你可以即時計算出它們的屬性。這裡是一個玩具範例:
class TT(object):
def __getattr__(self, name): return 23
import sys
sys.modules[__name__] = TT()
這段程式碼作為一個模組的首次匯入會以類別
TT
的一個實體覆寫模組的
sys.modules
項目。你試著從它取得的任何屬性名稱看似都會有整數值
23
自訂的匯入器(importers
Python 提供的一個進階但很少會用到的功能性是變更部分或全部 ...
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