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

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate 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.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

利用 Python 进行数据分析(原书第2版)

利用 Python 进行数据分析(原书第2版)

Wes McKinney

Publisher Resources

ISBN: 9789864766819