缺陷:__mian__不能使用相對導入
PEP 328 Relative Imports and __name__ 中說明:
Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
即:相對導入在 package 分層中,使用模塊的__name__ 屬性得到模塊的位置。但是如果模塊的名字沒有包含任何 package 信息(例如,__main__模塊),不管是否該模塊實際位於文件系統,相對導入會被當作頂層模塊導入(a top level module)。
修復
根據 6.4.2. Intra-package References 的建議:
Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.
__mian__ 使用 絕對導入
方式,而其他模塊仍使用 相對導入
if __name__ == '__main__':
sys.path.append(os.path.dirname(sys.path[0]))
后話
導入的方式
參考 stackoverflow vaultah 的回答,比較詳細,這里不再贅述。
為什么選擇相對導入的優勢
PEP 328 Rationale for Relative Imports 中說明:
Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages.In addition, a module inside a package can't easily import itself without relative imports.
即:相對導入可以對大型的 python packages 重構時,不用重新編輯 sub-packages;另外,相對導入可以比較輕松地導入自身。