我是 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/