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 技術手冊 第三版
模組載入
|
207
from ... import *
直接位在一個模組主體內(不是在函式或類別的主體內)的程式碼可以在
一個
from
述句中使用一個星號(
*
):
from mymodule import *
這個
*
請求的是模組
modname
的「所有(all)」屬性都被繫結為匯入端模
組(importing module)的全域變數。當模組
modname
有一個名為
__all__
的屬性,那個屬性的值會是由這種
from
述句所繫結的屬性名稱(attribute
names)所成的串列。否則的話,這種
from
述句會繫結
modname
的所有屬
性,除了以底線開頭的那些。
在你的程式碼中小心使用
from M import *
因為
from M import *
可能會繫結任意的一組全域變數,它
經常會有無法預見和不想要的副作用,例如隱藏 built-ins
重新繫結你仍然需要的變數。請非常保守地使用
*
形式的
from
,如果真的要用的話,並且只匯入文件有明確說明支援這
種用法的模組。
永遠不
使用這種形式的話,你的程式碼很有
可能會比較好,它最好只當成偶爾會在互動式 Python 工作階
段(interactive Python sessions)使用的一種方便的形式。
from vs. import
import
述句通常是比
from
述句更好的選擇。你可以把
from
述句,特別是
from M import *
這種形式,想成是只適合在互動式 Python 工作階段偶爾用
用的一種便利工具。當你永遠都以述句
import M
取用模組 ...
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