Python - warum kann ich import-Module ohne __init__.py überhaupt?

Ich bin neu in Python und ich habe immer noch nicht meinen Kopf herum, warum brauchen wir eine __init__.py file import Module. Ich habe durch die anderen Fragen und Antworten, wie diese.

Was mich verwirrt ist, dass ich importieren kann meine Module ohne __init__py, so warum brauche ich es überhaupt?

Meinem Beispiel,

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,

def hello():
    return 'Hello World from hello.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

Ergebnis,

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

Was es braucht ist nur diese zwei Zeilen,

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

Ohne __init__py. Kann mir jemand erklären, warum es funktioniert auf diese Weise?

Wenn __init__py ist der richtige Weg, was sollte ich tun/ändern in meinem code?

InformationsquelleAutor laukok | 2015-08-22
Schreibe einen Kommentar