Python包结构未导入正确的模块

2024-09-30 16:35:06 发布

您现在位置:Python中文网/ 问答频道 /正文

在PYPI文档之后,它展示了如何安装一个软件包,这非常有用。但是,一旦我将一个类引入到一个文件中,我就找不到该类。我附加了很多代码,但我认为上下文是必要的

现在,当我在目录中工作时,它可以正常工作,但是一旦它被上传到PYPI并在我的计算机上的其他地方使用,它就找不到类了

package_upload
├── EasyNN
│   ├── EasyNN.py
│   ├── __init__.py
│   └── import_this.py
├── LICENSE.txt
├── README.md
└── setup.py

Setup.py

import setuptools

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()


setuptools.setup(
    name='EasyNN',
    version='0.0.3',
    description='Currently Testing',
    packages=setuptools.find_packages(),
    python_requires='>=3.6',
    url="https://github.com/danielwilczak101/EasyNN",
    author="Daniel",
    author_email="daniel@gmail.com",
    long_description = long_description,
    long_description_content_type = "text/markdown",
    classifier=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)",
        "Operating System :: OS Independent",
        ],
    install_requires = ["matplotlib ~= 3.3.2",
                        "pytest>=3.7",
                        "tabulate >=0.8.7"
                        ],
    )

易新

import import_this

class NN:

    def say_hello(self):
        print("Hello NN World!")

导入_this.py

def foo():
    print("I've been imported")

运行Python代码

import EasyNN
nn = EasyNN.NN()

错误

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

Tags: 代码pyimportpypipackagessetupnndescription
1条回答
网友
1楼 · 发布于 2024-09-30 16:35:06

您正在尝试访问NN,它位于EasyNN/EasyNN.py的内部。如果要使NN类从顶级导入可用,则必须将其包含在顶级__init__.py文件中:

# EasyNN/__init__.py

from EasyNN import NN

然后,从软件包外部,计算机上的其他地方,NN现在可以从顶级导入获得

导入包时,无法直接访问该包中的文件中包含的对象。您需要将它们包含在相应包的__init__.py中,或者像这样访问它们:

from EasyNN.EasyNN import NN

在上面,第一个EasyNN是包,但第二个是名为EasyNN.py文件,它控制类NN

相关问题 更多 >