python - 无法从同一包导入 python 模块

标签 python import package

我目前正在用 python 编写一个库。我有一个名为 Selectors 的包作为库的子目录。我正在尝试在包中实现一个新模块,但是当我尝试导入它时出现错误:

NameError: name '_RaceSelector__ResultSelector' is not defined

我的目录如下所示:

Selectors
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── __pycache__
│   │   ├── SeasonSelector.cpython-38.pyc
│   │   ├── Selector.cpython-38.pyc
│   │   ├── __init__.cpython-38.pyc
│   │   ├── race_selector.cpython-38.pyc
│   │   ├── result_selector.cpython-38.pyc
│   │   └── season_selector.cpython-38.pyc
│   ├── race_selector.py
│   ├── race_selector.pyc
│   ├── result_selector.py
│   ├── result_selector.pyc
│   ├── season_selector.py
│   ├── season_selector.pyc
│   ├── selector.py
│   └── selector.pyc

我想使用race_selector.py中的模块,这是该文件:

from .selector import __Selector
from .result_selector import __ResultSelector

class RaceSelector(__Selector):

    data = []
    loaded_races = []
    header = []

    result_selector = __ResultSelector()

选择器.py

import os
import csv

class __Selector:
    def __init__(self, file_name):
        self.data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../data/' + file_name + '.csv')
        self.raw_data = self.load_data()
        self.data = self.get_data()

结果选择器.py

import os
from .selector import __Selector

class __ResultSelector(__Selector):
    def __init__(self):
        super().__init__('results')

我能够正常导入 selector 并按预期工作,但 result_selector 会产生错误。

谢谢

最佳答案

当您执行以下操作时:

result_selector = __ResultSelector()

Python 搜索 _RaceSelector__ResultSelector 因为有 2 个下划线。

PEP8 中所述:

If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.

关于python - 无法从同一包导入 python 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59424851/

相关文章:

python - 在 Python 中跟踪函数调用 + 闭包(à la SICP)的数量

python - 在 2D numpy 数组的子矩阵上高效运行

python - Google App Engine 模型的 JSON 序列化

python - cx_freeze 的 exe 错误

windows - 如何将 session 导入 MobaXterm?

Python: "import"更喜欢什么——模块还是包?

java - 当给定输入时调用不同类的包?

android - 从另一个 Android 应用程序获取图标

javascript - 从姊妹文件 Node.JS 导入函数

python - django - 导入错误 : no module named views