Skip to main content
 首页 » 编程设计

python之NameError: name 'self' is not defined"when using inside with 语句

2024年10月17日7JustinYoung

有人可以帮助我在“with”中使用“self”吗? 下面的代码抛出“NameError: name 'self' is not defined”。

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 来验证。您的代码片段适合我。