[英]python local module import problems
使用 Python 3.6
嗨,我有一个带有多个 PY 文件的 python 模块 - 我想保持名称层次结构,但不能。
实际上,我可以这样做:
from.DOTNAME import * <-- 有效
我实际上想要这个:
import.DOTNAME as NAME <-- 这不是。
我有例如
module:
__init__.py <-> module init
constants.py
contains: ONE =1 and TWO =2
foo.py
I want to refer to "constants.ONE" and "constants.ONE" but cannot
bar.py
I want to refer to "constants.ONE" and "constants.TWO" but cannot
我想做的是在 foo 和 bar.py 中,将本地模块 constants.py(PY 文件)作为常量导入,从而保持“常量”前缀
为此,在文件 foo.py 中,我这样做:
导入常量 - 但不能,它说:没有这样的模块 - 这只发生在模块之外的模块中
我可以这样做:import.constants *,但是我不能使用constants.ONE或constants.TWO,我需要使用名称ONE和TWO,我想清楚地将它们标识为constants.ONE和constants.TWO(与其他模块中的其他方法/功能)
如何导入本地模块(py 文件)但将模块名称保留为我想避免使用 IMP() 的前缀 - 我在其他地方看到过一种方法表明这一点,我认为这不是正确的或 pythonic 方式
您可以在 constant.py 中创建一个 class 并将 ONE 和 TWO 分配为 class 属性:
class Constant:
ONE = 1
TWO = 2
然后从 constant.py 模块导入常量 class
from .constant import Constant
print(Constant.ONE)
print(Constant.TWO)
在您的foo.py
中,您需要执行以下操作:
import module.constants as constants
print(consants.ONE,constants.TWO)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.