简体   繁体   English

如何在Python中定义子模块?

[英]How to define a sub-module in Python?

Python has a module named "os". Python有一个名为“os”的模块。 It also has some other module named "os.path" which is categorized under the "os". 它还有一些名为“os.path”的模块,它被归类为“os”。

I can use "os.path" methods even if only import the "os" module. 即使只导入“os”模块,我也可以使用“os.path”方法。

import os

print(os.path.join("sdfs","x"))

I wonder how can I define a sub-module like this? 我想知道如何定义这样的子模块?

That's the __init__.py 'magic' of the os module - it imports its submodule path to its namespace, essentially giving you a way to access the latter even if you only import os . 这是os模块的__init__.py '魔术' - 它将其子模块path导入其命名空间,实际上即使您只导入os也可以访问后者。

os
|- path
   |- __init.__.py    # 2
|- __init__.py        # 1

The first __init__.py (#1) essentially has import .path so whenever you import just os , it imports path in its namespace, and therefore you can access it as os.path . 第一个__init__.py import .path (#1)本质上具有import .path因此每当你导入os ,它都会在其命名空间中导入path ,因此你可以将它作为os.path访问。

(NOTE: This is not exactly the case with the os module, but that's how to essentially achieve it) (注意:这与os模块不完全相同,但这是如何实现它的)

Use this structure: 使用此结构:

/ Package
├── __init__.py
├── file.py
│
├─┐ subpackage
│ ├── __init__.py
│ └── file.py
│
└─┐ subpackage2
  ├── __init__.py
  └── file.py

Note each subpackage has its own __init__.py file. 请注意,每个子包都有自己的__init__.py文件。 This will make Package.subpackage behave like os.path , importation speaking (considering you do not import .subpackage under the main __init__ file of Package ). 这将使Package.subpackage表现得像os.path ,进口来讲(考虑不导入.subpackage主要根据__init__的文件Package )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM