Jak*_*rne 9 python python-module python-3.x
我已经浏览并发现了很多问题和很多答案,但似乎没有任何问题。
我设置了两个文件config.py和test.py名为test一个文件夹下。
配置包括代码:
class Config:
def __init__(self, name):
self.name = name
Run Code Online (Sandbox Code Playgroud)
而测试有:
try:
# Trying to find module in the parent package
from . import config
print(config.debug)
del config
except ImportError:
print('Relative import failed')
try:
# Trying to find module on sys.path
import config
print(config.debug)
except ModuleNotFoundError:
print('Absolute import failed')
Run Code Online (Sandbox Code Playgroud)
这已根据此堆栈答案的答案供应商汇总在一起。
不幸的是,我同时出现了两个错误,当我尝试直接调用它时,from config import Config我得到 ModuleNotFoundError
我真的对这个迷失了方向,不知道从哪里开始。
使用 Python 3.6,atom.io 作为我的 IDE。
小智 2
#test.py
class Test:
try:
# Trying to find module in the parent package
from . import config
print(config.Config.debug)
del config
except ImportError:
print('Relative import failed')
try:
# Trying to find module on sys.path
import config
print(config.Config.debug)
except ModuleNotFoundError:
print('Absolute import failed')
#config.py
class Config:
debug = True
def __init__(self, name):
self.name = name
Run Code Online (Sandbox Code Playgroud)
#config.py
在此文件中,出现错误是因为没有变量 debug = True
class Config:
debug = True
def __init__(self, name):
self.name = name
Run Code Online (Sandbox Code Playgroud)
#测试.py
在此文件中,出现错误是因为您正在执行文件导入的打印并尝试以直接方式访问变量,也就是说,您需要 3 个步骤... import、class、variable >>>配置.配置.调试
print(config.Config.debug)
Run Code Online (Sandbox Code Playgroud)
我希望它对你有帮助