导入错误无法从y导入名称x

2024-10-04 09:17:51 发布

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

在python模块上导入类时遇到问题

以下是我的目录结构:

TestMap
  +lib
    +vendors
      +testing
       - _init.py
       - products.py
    - _init_py.
    - notifications.py
    - scraper.py
    - utils.py
  -main.py

我从scraper.py开始,尝试在products.py上获取函数,它是vendors -> testing -> products.py

from .vendors.testing.products import TestProducts

我想做的是:

ImportError: cannot import name 'TestProducts' from 'lib.vendors.testing.products' (C:\Users\Annoynmous\Desktop\TestMap\lib\vendors\testing\products.py)

在products.py中,类名是:

class TestProducts():

而我却不知道我到底做错了什么


Tags: 模块frompyimport目录initlibscraper
2条回答

在scraper.py中尝试此操作

from vendors.testing.products import TestProducts

import vendors.testing.products as product 
class scraper:
    def __init__(self):
        self.product = product.TestProducts()

使用self.product访问类scraper中TestProducts的任何函数

使用pythonpath在项目中设置源目录:

export PATH=$PATH:/home/user/somepath/TestMap 

并从该源路径导入模块

from lib.vendors.testing.products import TestProducts

或者使用__init__.py文件定义内部模块目录,并使用直接模块名导入模块

相关问题 更多 >