【发布时间】:2018-03-26 21:04:34
【问题描述】:
我是 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 是正确的方法,我应该做什么/更改我的代码?
【问题讨论】:
标签: python python-2.7 mod-wsgi