我想将三个与数据库相关的类组合到一个包中,结构如下:
adodb_pyodbc /
__init__.py # empty
PyConnection.py
PyRecordset.py
PyField.py
此软件包位于我的Lib / site-packages文件夹中。
在此次尝试的早期迭代中,我没有使用“Py”前缀,并且我收到一个错误,抱怨module.__init__()
只接受两个参数,其中三个被传递给它。有人建议名称“Recordset”可能与其他东西冲突,所以我改变了它。
当文件与使用它们的项目位于同一文件夹中时,这些类可以正常工作。在这种情况下,我可以使用:
PyRecordset.py:
from PyConnection import PyConnection
from PyField import PyField
class PyRecordset: pass
DerivedSet.py
from PyRecordset import PyRecordset
class DerivedRecordset(PyRecordset): pass
但是当它们位于包内时,相同的文件不起作用。我的测试程序从这一行开始:
from adodb_pyodbc import PyConnection as Connection
当我运行它时,我收到此错误消息:
C:\Python35\python.exe "C:/Customers/Nucor Crawfordsville/Scripts/64 bit/Testing/cpsa_simulator.py"
Traceback (most recent call last):
File "C:/Customers/Nucor Crawfordsville/Scripts/64 bit/Testing/cpsa_simulator.py", line 8, in <module>
from Level3_CoilsSet import Level3_CoilsSet
File "C:\Customers\Nucor Crawfordsville\Scripts\64 bit\Testing\Level3_CoilsSet.py", line 1, in <module>
from adodb_pyodbc import PyRecordset as Recordset
File "C:\Python35\lib\site-packages\adodb_pyodbc\PyRecordset.py", line 9, in <module>
from PyConnection import PyConnection
ImportError: No module named 'PyConnection'
但是当在PyCharm中编辑PyRecordset.py时,它似乎能够找到PyConnection.py文件。
我尝试在PyConnection.py中使用相对寻址:
from . import PyConnection
from . import PyField
但这让我回到__init__()
错误:
C:\Python35\python.exe "C:/Customers/Nucor Crawfordsville/Scripts/64 bit/Testing/cpsa_simulator.py"
Traceback (most recent call last):
File "C:/Customers/Nucor Crawfordsville/Scripts/64 bit/Testing/cpsa_simulator.py", line 8, in <module>
from Level3_CoilsSet import Level3_CoilsSet
File "C:\Customers\Nucor Crawfordsville\Scripts\64 bit\Testing\Level3_CoilsSet.py", line 3, in <module>
class Level3_CoilsSet(Recordset):
TypeError: module.__init__() takes at most 2 arguments (3 given)
我该怎么做?
非常感谢你的帮助。与此同时,我将从包中取出这些文件并将它们放回我的测试项目中。我在这个问题上浪费了太多时间。
答案 0 :(得分:2)
当您从包外部使用PyConnection
时,您必须从定义它的模块中导入它:
from adodb_pyodbc.PyConnection import PyConnection as Connection
或者,更方便的是,将其导入包init文件adodb_pyodbc/__init__.py
:
from .PyConnection import PyConnection
然后,从外面看,你可以这样做:
from adodb_pyodbc import PyConnection as Connection