我目前正在用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()
selector.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
import os
from .selector import __Selector
class __ResultSelector(__Selector):
def __init__(self):
super().__init__('results')
我能够很好地导入selector
并按预期工作,但是result_selector会产生错误。
谢谢
答案 0 :(得分:3)
执行以下操作时:
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.