我的包层次结构:
InstrumentController/
__init__.py
instruments/
__init__.py
_BaseInstrument.py
Keithley2000.py
# etc...
仪器文件的内容:
# _BaseInstrument.py
class _BaseInstrument(object):
"""Base class for instruments"""
# etc...
# Keithley2000.py
from InstrumentController.instruments._BaseInstrument import _BaseInstrument
class Keithley2000(_BaseInstrument):
# etc...
我希望我的用户能够访问这些类,而不必深入研究模块的层次结构。他们只需键入 from InstrumentController.instruments import Keithley2000
,而不是 from InstrumentController.instruments.Keithley2000 import Keithley2000
。
为此,我在 InstrumentController.instruments.__init__
中有一堆这样的行:
from .Keithley2000 import Keithley2000
from .StanfordSR830 import StanfordSR830
# etc...
所以现在这些类位于包命名空间的顶部,而不是子模块中。我的问题是:这是个好主意吗?这些类与其所属的模块同名,因此在顶层导入该类会使模块不可用。这让我有点不安 - 有更好的方法吗?
最佳答案
您的做法是可以接受的,但我建议您将所有包/模块名称重新设置为小写,如 1) 这是惯例 specified in PEP 8 , 和 2) 它将消除您的阴影问题。
关于python - 代码风格 - "flattening"包的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12626336/