1

我在使用“import module”而不是“from module import ...”语法时遇到了问题。这清楚地表明我对加载模块的理解是不够的。据我在其他地方发现,这种差异主要是样式问题,但这并不能解释以下情况。

我安装了 ase 使用

sudo apt install python3-ase

我尝试了以下方法:

import ase
ase.io.read

哪个输出

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ase' has no attribute 'io'

然而,当尝试

from ase.io import read
read

或者——也可能——

from ase.io import read
import ase
ase.io.read

我得到输出

<function read at 0x7f33dc721730>

后者是想要的结果,因为我想使用 ase.io.read 函数来读取 .cif 文件。

有关问题根源的更多信息显示在以下 python 会话中:

import sys
import ase
sys.modules['ase']

来自“/home/vanbeverj/Programs/anaconda3/envs/abienv/lib/python3.6/site-packages/ase/init .py”的模块“ ase

dir(ase)

['Atom', 'Atoms', 'LooseVersion', ' all ', ' builtins ' , ' cached ', ' doc ', ' file ', ' loader ', ' name ', ' package ', ' path ', '规格','版本','ase','atom','atoms','calculators','cell','constraints','data','dft','formula','geometry','np' , 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

from ase.io import read
dir(ase)

['Atom', 'Atoms', 'LooseVersion', ' all ', ' builtins ' , ' cached ', ' doc ', ' file ', ' loader ', ' name ', ' package ', ' path ', '规格','版本','ase','atom','atoms','calculators','cell','constraints','data','dft','formula','geometry','io' , 'np', 'parallel', 'symbols', 'sys', 'transport', 'units', 'utils']

'dir(ase)' 命令有明显不同的输出。例如 io 子模块会发生什么?有人可以解释一下引擎盖下发生了什么吗?

4

2 回答 2

2

是否将导入的子模块作为属性公开,或者是否完全导入子模块取决于每个包。

os,例如,确实导入和暴露os.path

在您的情况下,ase不会子模块公开ioase. (是否io进口是另一回事;您可以检查sys.modules。)

于 2020-02-19T14:21:45.300 回答
1

我觉得好像tkinter。在tkinter,如果我们想使用ttk,我们必须使用

import tkinter
from tkinter import ttk 

如果我们使用

import tkinter

.......
btn = tkinter.ttk.Button(xxxxxx)

然后它会显示AttributeError: module 'tkinter' has no attribute 'ttk'

可以看到ase模块源码。在 ase> __init__.pyfile 中,import ase表示导入所有的类或函数__init__.py

from ase import io,也许这意味着它将io在ase文件夹中导入模块(io是一个独立的.py文件)

于 2020-02-19T14:27:24.170 回答