Python 包导入和命名错误
我在进口自制模块时遇到了一些麻烦,我只是看不出我做错了什么 我有一个名为basics的包,它包含了我所有的基类 我有第二个名为components的包,components中的每个模块都使用basics中的模块。 我有一个脚本文件,位于另一个文件夹中,它调用了basics和components模块 我得到以下错误:Python 包导入和命名错误,python,python-2.7,namespaces,python-import,Python,Python 2.7,Namespaces,Python Import,我在进口自制模块时遇到了一些麻烦,我只是看不出我做错了什么 我有一个名为basics的包,它包含了我所有的基类 我有第二个名为components的包,components中的每个模块都使用basics中的模块。 我有一个脚本文件,位于另一个文件夹中,它调用了basics和components模块 我得到以下错误: Traceback (most recent call last): File "<stdin>", line 1, in <module> File
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "H:/scripts/CIF_utilities/scripts/hello world.py", line 11, in <module>
TW=TextWriter(r'H:/scripts/CIF_utilities/components')
File "H:\scripts\CIF_utilities\components\textwriter.py", line 23, in __init__
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
NameError: global name 'Layout' is not defined
textwriter.py是给出错误的一个。在init中,我使用Layout类(将进行导入)从预格式化文件加载一些数据
在textwriter.py中
#texwriter.py
import basics
import os, os.path, sys
import re
from numpy import *
from scipy import *
class TextWriter:
def __init__(self,pathToCIF=None):
if pathToCIF==None:
path=os.path.split(textwriter.__file__)[0]
else:
path=pathToCIF
###line that crashes is here
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
self.alphabet=layout.workCell
有layout.py类:
#layout.py
import basics
from numpy import *
from scipy import *
import Tkinter
import tkFileDialog
import os, os.path
import re
import datetime
class Layout:
countCell=0
@classmethod
def getNewNumber(self):
Layout.countCell+=1
return Layout.countCell
def __init__(self,File=None):
self.cellList=[]
self.layerList=[]
self.nameFile=""
self.comments=""
self.workCell=None
if File!=None:
self.importCIF(File)
basics包的init.py包含所有必要的导入:
#__init__.py in basics folder
from baseElt import *
from cell import *
from layout import *
from transformation import *
来自组件的init.py为空
我目前使用的是Anaconda64位发行版(如果我记得很清楚的话,是python 2.7)
谢谢你急需的帮助 由于
Layout
是在basics/\uuuu init\uuuu.py
中导入的,因此它只存在于basics
命名空间中,而不存在于helloworld.py
中。或者使用
layout = basics.Layout()
或者使用将Layout
显式导入helloworld.py
from basics import Layout
在textwriter.py中,您要切换
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
为了
您的代码中可能存在类似的问题。值得注意的是,它不是pythonic
from package import *
建议改为使用
from package_or_module import specific_item
import package_or_module
请记住,如果您使用常规的
import
导入,则必须使用模块/包名称来访问所需的对象(即basics.Layout
)。不应该是basics.Layout(…)
(或从基本导入布局
)?我将“导入基本”更改为“从基本导入*”,现在它可以工作了!我将使用一些更高级的脚本再试一次,看看它是否也适用于此
from package import *
from package_or_module import specific_item
import package_or_module