理解Python的导入方式

3
在学习Django和Python的过程中,我无法理解这个问题。(示例注释:'helloworld'是我的项目名称,它有1个名为'app'的应用程序。)
from helloworld.views import *          # <<-- this works
from helloworld import views            # <<-- this doesn't work
from helloworld.app import views        # <<-- but this works.  why?

似乎第二行和第三行代码实际上是相同的,为什么第二行不起作用?

编辑--添加了两个文件的来源。 您可能会从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())

helloworld/app/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())

发布helloworld的实际源代码是什么? - user447688
import helloworld.views as views 这样写可以吗? - SingleNegationElimination
你有一个名为 helloworld/init.py 的文件吗? - SingleNegationElimination
是的,有helloworld/init.py文件。 - T. Stone
3个回答

11

Python的导入功能可以导入两种不同类型的内容:模块和对象。

import x

导入名为x的整个模块。

import x.y

导入一个名为y的模块及其容器x。您可以通过x.y进行引用。

然而,创建它时,您需要创建此目录结构。

x
    __init__.py
    y.py

当你添加导入语句时,你可以识别出特定的对象从模块中提取并移动到全局命名空间。
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

如果helloworld是一个包(一个带有__init__.py文件的目录),通常不包含任何对象。
from x import y # isn't sensible
import x.y # importing a whole module.

有时候,您会在__init__.py文件中定义对象。
通常使用"from module import x"从模块中选择特定的对象。
使用import module导入整个模块。

那么 "from helloworld import views" 最好写成 "import helloworld.views",是这样理解吗? - T. Stone
@T. Stone:正确。标准库示例是import os.path - S.Lott

4
from helloworld.views import *          # <<-- this works
from helloworld import views            # <<-- this doesn't work
from helloworld.app import views        # <<-- but this works.  why?

#2和#3不相同。

第二个从包helloworld中导入views。第三个从helloworld的子包helloworld.app中导入views。这意味着视图是特定于您的Django应用程序而不是您的项目的。如果您有单独的应用程序,如何从每个应用程序中导入视图?您必须指定要从中导入的应用程序的名称,因此使用语法helloworld.app


1
正如sykora所暗示的那样,helloworld本身并不是一个包,因此#2不能起作用。您需要一个正确设置的helloworld.py文件。
我几天前询问了import的事情,这可能会有所帮助: Lay out import pathing in Python, straight and simple?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接