Python-为什么我可以完全不使用__init__.py导入模块? [英] Python - why can I import modules without __init__.py at all?

查看:137
本文介绍了Python-为什么我可以完全不使用__init__.py导入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我仍然无法理解为什么我们需要__init__.py文件来导入模块.我还经历了其他问题和答案,例如.

I'm new to Python and I still can't get my head around why we need a __init__.py file to import modules. I have gone through other questions and answers, such as this.

让我感到困惑的是,我可以不导入 来导入模块,所以为什么我完全需要它?

What confuses me is that I can import my modules without __init__py, so why do I need it at all?

我的例子,

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]

modules/hello/hello.py

modules/hello/hello.py,

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

modules/hello/HelloWorld.py

modules/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.有人可以解释为什么以这种方式起作用吗?

Without any of __init__py. Can someone explain why it works in this way?

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

If __init__py is the proper way, what should I do/change in my code?

推荐答案

我认为这是一个很好的.

I think this is a good 'answer' for what I didn't understand.

myMath/
    __init__.py
    adv/
        __init__.py
        sqrt.py
        fib.py
    add.py
    subtract.py
    multiply.py
    divide.py

myMath/__ init __.py

from add import add
from divide import division
from multiply import multiply
from subtract import subtract
from adv.fib import fibonacci
from adv.sqrt import squareroot

index.py

import sys

sys.path.append('C:\Users\mdriscoll\Documents')

import mymath

print mymath.add(4,5)
print mymath.division(4, 2)
print mymath.multiply(10, 5)
print mymath.fibonacci(8)
print mymath.squareroot(48)

这篇关于Python-为什么我可以完全不使用__init__.py导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆