python - 名称错误:名称 'self' 未定义”在 with 语句内部使用时

标签 python class nameerror contextmanager

有人可以帮助我在“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/

相关文章:

Java/BlackBerry 构建错误覆盖太多类

即使我导入了集合,也没有定义 python 全局名称 'collections'

python - Django 名称错误 urls.py

python - Pandas 按日期过滤 CSV

python - 如何在 python 中找到几种类型的最近共同祖先(基本类型)?

Java 枚举 - 稍后转换的存储类型

ruby - Ruby 未知类的目的是什么?

python - 如何获取Spark决策树模型的节点信息

python - python使用正则表达式删除重复字符串

python - NameError:名称 '' 未定义