Py学习  »  Django

为什么从django导入*不能导入所有子模块?

scrapy • 6 年前 • 2456 次点击  

from modue_name import * ,表示导入模块名中的所有子模块。

ls /usr/local/lib/python3.5/dist-packages/django
apps  contrib  dispatch  __init__.py  __pycache__   templatetags  utils
bin   core     forms     __main__.py  shortcuts.py  test          views
conf  db       http      middleware   template      urls

子模块 apps 位于 django

import django
from django import *
print(django.apps)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'django' has no attribute 'apps'

为什么是子模块 应用程序 from django import * ?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54417
文章 [ 5 ]  |  最新文章 6 年前
MrBrN197
Reply   •   1 楼
MrBrN197    6 年前

你说得对,这就是你所做的;你已经导入了django中的所有模块,但是apps是django中的一个文件夹,它是另一个你必须显式导入该包的包

mzjn
Reply   •   2 楼
mzjn    6 年前

没有 __all__ django/__init__.py . 这就是为什么通配符导入 from django import * 不起作用。

见 https://docs.python.org/3/tutorial/modules.html#importing-from-a-package Can someone explain __all__ in Python? .

funnydman
Reply   •   3 楼
funnydman    6 年前

首先,最好将需求安装到虚拟环境中,而不是系统Python中。值得注意的是,从Python3.3开始 venv 添加了模块,使此过程简单明了。

# globally load the module, let's check what's inside.
>>> import django
>>> dir(django)  # only the content from the __init__.py was imported.
['VERSION', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
 '__name__', '__package__', '__path__', '__spec__', '__version__', 
'get_version', 'setup', 'utils']
>>> from django import *
>>> print(django.apps)
>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'django' has no attribute 'apps'

>>> globals() # no Django submodules were loaded. 

同时在Django shell中运行上述命令:

>>> import django
>>> dir(django)
['VERSION', '__builtins__','__cached__','apps','setup','template',
'templatetags','urls','utils', 'views', ...]
>>> print(django.apps)
>>> <module 'django.apps' from .../django/apps/__init__.py>
>>> globals() # some of the Django submodules were loaded 

在控制台中进行全局Django导入时,来自 __init__.py django 导入也使子模块可用。

Arakkal Abu
Reply   •   4 楼
Arakkal Abu    6 年前

apps 模块在您的上下文中,您可以通过两种方式(至少)执行此操作

方法-1

import django.apps

print(django.apps)

应该是 import django.apps 而不是 import django

方法2

from django import apps

print(apps)

from django import * ,Python将只导入 .py ) __init__.py . 即 将不可用,因为 不是模块 但是

MrBrN197
Reply   •   5 楼
MrBrN197    6 年前

星号(*)在from modue_name import*中用作通配符,它表示导入模块名称中的所有子模块。

某种程度上。

模块

from <module_name> import * . 如果我们讨论的是一个模块(一个类似于 tools.py ). 这种模块没有子模块,所以说

意思是导入模块名中的所有子模块。

包裹

__init__.py 文件,所以它是一个包。在这种情况下打电话 from <package_name> import * __初始年 包的文件,但默认情况下不会导入包中的其他子模块 除非 你定义了 __all__

# __init__.py
__all__ = ['apps']

包还可以显式地导入 __初始年 这使得子模块在使用 从<包名称>导入*

# __init__.py
import django.apps

这也是供应商的工作。

解决方案

from django.apps import <what_you_need>

干净多了