我是Python新手,但仍然无法理解为什么我们需要使用__init__.py
文件导入模块。我已经通过其他问题和答案,如this。Python - 为什么我可以导入没有__init__.py的模块?
什么让我困惑的是,我可以导入我的模块没有__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.py,
def hello():
return 'Hello World from hello.py!'
模块/你好/ 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
是正确的方法,我该怎么做/更改我的代码?
包的另一大优势是分离的命名空间下降。如果你编写你自己的'json'模块,它将会影响全局'json'模块。但是如果你将其设置为'mypackage.json',它不会导致这样的冲突(至少在Python 3或Python 2中,from __future__ import absolute_import')。 – Blckknght
谢谢。你能给我看一个需要'__init __。py'的包的例子吗?谢谢。 – laukok
@teelou:在3.3版之前的Python版本中,所有包都被* required *为'__init __。py'文件。 Python 3.3删除了这个要求,参见[PEP 420](https://www.python.org/dev/peps/pep-0420/)。听起来你可能对包还不是很了解,所以在阅读PEP之前,你可能想阅读[Python文档的适当部分](https://docs.python.org/2/tutorial/modules.html #packages)首先。 – Blckknght