简体   繁体   English

无法从同一个包中导入 python 模块

[英]Unable to import python module from same package

I'm currently writing a library in python.我目前正在用 python 编写一个库。 I have a package called Selectors as a sub-directory of the library.我有一个名为Selectors的包作为库的子目录。 I am trying to implement a new module in the package, but when I try to import it I get the error:我正在尝试在包中实现一个新模块,但是当我尝试导入它时出现错误:

NameError: name '_RaceSelector__ResultSelector' is not defined

My directory looks like this:我的目录是这样的:

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

I want to use the modules in race_selector.py , here is that file:我想使用race_selector.py的模块,这是该文件:

from .selector import __Selector
from .result_selector import __ResultSelector

class RaceSelector(__Selector):

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

    result_selector = __ResultSelector()

selector.py选择器.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()

result_selector.py result_selector.py

import os
from .selector import __Selector

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

I am able to import selector just fine and works as intended, but result_selector produces the error.我能够很好地导入selector并按预期工作,但 result_selector 产生错误。

Thanks谢谢

When you do the following:当您执行以下操作时:

result_selector = __ResultSelector()

Python searches for _RaceSelector__ResultSelector because there is 2 underscores. Python 搜索_RaceSelector__ResultSelector因为有 2 个下划线。

As mentioned in PEP8 :正如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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM