了解python导入

T. *_*one 3 python django import

在学习Django和Python的过程中.我无法理解这一点.

(示例注释:'helloworld'是我项目的名称.它有一个名为'app'的应用程序.)

from helloworld.views import *          # <<-- this works
from helloworld import views            # <<-- this doesn't work
from helloworld.app import views        # <<-- but this works.  why?
Run Code Online (Sandbox Code Playgroud)

似乎第2行和第3行实际上是相同的.为什么#2不起作用?

编辑 - 添加了两个文件的来源. 您可能会从Django Book项目中识别此代码(http://www.djangobook.com/en/2.0)

的HelloWorld/views.py

from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404
import datetime

def hello(request):
    return HttpResponse("Hello world")


def current_datetime(request):
    current_date = datetime.datetime.now()
    return render_to_response('current_datetime.html', locals())


def offset_datetime(request, offset):
    try:
        offset = int(offset)
    except ValueError:
        raise Http404()

    next_time = datetime.datetime.now() + datetime.timedelta(hours=offset)
    return render_to_response('offset_datetime.html', locals())

def display_meta(request):
    values = request.META.items()
    values.sort()
    path = request.path
    return render_to_response('metavalues.html', locals())
Run Code Online (Sandbox Code Playgroud)

的HelloWorld /应用程序/ views.py

from django.shortcuts import render_to_response

def search_form(request):
    return render_to_response('search_form.html')

def search(request):
    if 'q' in request.GET:
        message = 'You searched for: %r' % request.GET['q']
    else:
        message = 'You searched for nothing.'

    return render_to_response('search_results.html', locals())
Run Code Online (Sandbox Code Playgroud)

S.L*_*ott 10

Python导入可以导入两种不同的东西:模块和对象.

import x
Run Code Online (Sandbox Code Playgroud)

导入名为的整个模块x.

import x.y
Run Code Online (Sandbox Code Playgroud)

导入名为的模块y及其容器x.你指的是x.y.

但是,在创建它时,您创建了此目录结构

x
    __init__.py
    y.py
Run Code Online (Sandbox Code Playgroud)

添加到import语句时,可以标识要从模块中提取的特定对象并移动到全局命名空间中

import x # the module as a whole
x.a # Must pick items out of the module
x.b

from x import a, b # two things lifted out of the module
a # items are global
b
Run Code Online (Sandbox Code Playgroud)

如果helloworld是一个包(一个目录,带有一个__init__.py文件),它通常不包含任何对象.

from x import y # isn't sensible
import x.y # importing a whole module.
Run Code Online (Sandbox Code Playgroud)

有时,您将在__init__.py文件中定义对象.

通常,使用"from module import x"从模块中挑选特定对象.

使用import module导入整个模块.