Qtwidgets 文件是在PyQt5 目录中编译的.so 文件,与所有模块一样,__init__.py 文件中没有导入,因此您需要使用 from ...
在py3 目录中使用cython 编译文件test1.cpython-34m.so 和空__init.__py 的示例表现出相同的行为:
In [1]: import py3
In [2]: py3.test1
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-2-9aa45b2a49b6> in <module>()
----> 1 py3.test1
AttributeError: 'module' object has no attribute 'test1'
In [3]: from py3 import test1
In [4]: test1.foo()
Out[4]: 100
PyQt5中的文件如下:
/usr/lib/python3/dist-packages/PyQt5$ ls
__init__.py
__pycache__
_QOpenGLFunctions_2_0.cpython-34m-x86_64-linux-gnu.so
QtCore.cpython-34m-x86_64-linux-gnu.so
Qt.cpython-34m-x86_64-linux-gnu.so
QtDBus.cpython-34m-x86_64-linux-gnu.so
QtDesigner.cpython-34m-x86_64-linux-gnu.so
QtGui.cpython-34m-x86_64-linux-gnu.so
QtHelp.cpython-34m-x86_64-linux-gnu.so
QtNetwork.cpython-34m-x86_64-linux-gnu.so
QtOpenGL.cpython-34m-x86_64-linux-gnu.so
QtPrintSupport.cpython-34m-x86_64-linux-gnu.so
QtTest.cpython-34m-x86_64-linux-gnu.so
QtWidgets.cpython-34m-x86_64-linux-gnu.so
uic
使用cat可以看到__init__.py中没有导入:
$:/usr/lib/python3/dist-packages/PyQt5$ cat __init__.py
# Copyright (c) 2014 Riverbank Computing Limited <info@riverbankcomputing.com>
#
# This file is part of PyQt5.
#
# This file may be used under the terms of the GNU General Public License
# version 3.0 as published by the Free Software Foundation and appearing in
# the file LICENSE included in the packaging of this file. Please review the
# following information to ensure the GNU General Public License version 3.0
# requirements will be met: http://www.gnu.org/copyleft/gpl.html.
#
# If you do not wish to use this file under the terms of the GPL version 3.0
# then you may purchase a commercial license. For more information contact
# info@riverbankcomputing.com.
#
# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
因此,由于__init__.py 中没有导入,当您尝试使用 PyQt5.Qtwidgets 时,您会收到错误,因为模块显然没有属性。
如果您在__init__.py 中添加了类似from . import QtWidgets 的内容,那么您可以使用import PyQt5 PyQt5.Qtwidgets 或PyQt5.Qtwidgets 在您从packageQtwidgets 时也可以使用空白初始化/强>PyQt5。
当你import PyQt5你时,你可以看到你实际上有一个模块:
In [6]: import PyQt5
In [7]: type(PyQt5)
Out[7]: module
因此,真正的区别以及您看到输出的原因是您尝试从第二个示例中的 module 和第一个示例中的 package 导入。