首页 / PYTHON / 了解python导入
了解python导入
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了了解python导入,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2148字,纯文字阅读大概需要4分钟。
内容图文
![了解python导入](/upload/InfoBanner/zyjiaocheng/763/4709e52c61194db282823720302abe6e.jpg)
在学习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?
似乎第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())
的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())
解决方法:
Python导入可以导入两种不同的东西:模块和对象.
import x
导入名为x的整个模块.
import x.y
导入名为y的模块和它的容器x.你指的是x.y.
但是,在创建它时,您创建了此目录结构
x
__init__.py
y.py
添加到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
如果helloworld是一个包(一个目录,带有__init__.py文件),它通常不包含任何对象.
from x import y # isn't sensible
import x.y # importing a whole module.
有时,您将在__init__.py文件中定义对象.
通常,使用“from module import x”从模块中挑选特定对象.
使用导入模块导入整个模块.
内容总结
以上是互联网集市为您收集整理的了解python导入全部内容,希望文章能够帮你解决了解python导入所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。