有人可以帮助我在“with”中使用“self”吗? 下面的代码抛出“NameError:名称'self'未定义”。
class Versions:
def __init__(self):
self.module_a = '1.0.0'
self.module_b = '1.0.0'
if os.path.exists('config.json'):
with open('config.json') as f:
configs = json.load(f)
for config in configs:
setattr(self, config, configs[config])
回溯
NameError Traceback (most recent call last)
<ipython-input-5-ed6a4ca551d4> in <module>()
3 configs = json.load(f)
4 for config in configs:
----> 5 setattr(self, config, configs[config])
6
NameError: name 'self' is not defined
谢谢。
最佳答案
请检查您的缩进 - 如果您混合使用空格和制表符,则可能会发生这种情况;使用 $python -tt 进行验证。你的代码片段对我来说效果很好。
关于python - 名称错误:名称 'self' 未定义”在 with 语句内部使用时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39890999/