Python - 为什么我可以在没有 __init__.py 的情况下导入模块?

标签 python python-2.7 mod-wsgi

我是 Python 新手,但我仍然无法理解为什么我们需要一个 __init__.py 文件来导入模块。其他的问答我都看过了,比如this .

让我感到困惑的是,我可以没有 __init__py导入我的模块,所以我为什么需要它

我的例子,

index.py
   modules/
      hello/
          hello.py
          HelloWorld.py

index.py,

import os
import sys

root = os.path.dirname(__file__)
sys.path.append(root + "/modules/hello")

# IMPORTS MODULES
from hello import hello
from HelloWorld import HelloWorld

def application(environ, start_response):

    results = []

    results.append(hello())

    helloWorld = HelloWorld()
    results.append(helloWorld.sayHello())

    output = "<br/>".join(results)

    response_body = output

    status = '200 OK'

    response_headers = [('Content-Type', 'text/html'),
                       ('Content-Length', str(len(response_body)))]

    start_response(status, response_headers)

    return [response_body]

模块/hello/hello.py,

def hello():
    return 'Hello World from hello.py!'

模块/hello/HelloWorld.py,

# define a class
class HelloWorld:
    def __init__(self):
        self.message = 'Hello World from HelloWorld.py!'

    def sayHello(self):
        return self.message

结果,

Hello World from hello.py!
Hello World from HelloWorld.py!

只需要这两行,

root = os.path.dirname(__file__)
sys.path.append(root + "/modules/hello")

没有任何 __init__py。有人可以解释为什么它以这种方式工作吗?

如果 __init__py 是正确的方法,我应该做什么/更改我的代码?

最佳答案

基于 this链接:从 Python 3.3 开始

Allowing implicit namespace packages means that the requirement to provide an __init__.py file can be dropped completely

关于Python - 为什么我可以在没有 __init__.py 的情况下导入模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32152373/

相关文章:

python - 当我在开始时得到几行新行时,如何从字母表开始打印

python - 使用 python (3.3.1) 在 html 源代码中搜索字符串

python - 使用 bool 表达式分配字符串

python - 将字典导入python脚本?

apache - 试图在 Apache : error 13 (search permissions missing) 上运行 Flask

初级开发面试中的Python代码测试

具有字符串连接和延续的 Python str.format

python - 是否可以从模块中删除方法?

python - 我可以在 Python 2.7 上运行一些 mod_wsgi 应用程序,而将其余应用程序保留在 Python 2.5 上吗?

python - Apache2&Django - NameError : name "AttributeError" is not defined