Skip to main content
 首页 » 编程设计

Python:使用嵌套类时出现 NameError

2025年05月04日15www_RR

我遇到了以下错误:

NameError: name 'JsonCleaner' is not defined 

导致错误的行是字典 ERROR_CODES_MAPPING_DICT 中的第一对(参见下面的代码):

from sshop.engine.models import WrongJsonError 
 
class JsonCleaner: 
 
 
    class NormalizeError(Exception): 
 
        ERROR_NO_CODE = 0 
        ERROR_TYPE_MISMATCH = 1 
        ERROR_WRONG_VALUE = 2 
        ERROR_LACK_OF_FIELD = 3 
 
        def __init__(self, error_desc, error_code=ERROR_NO_CODE): 
            self.error_desc = error_desc 
            self.error_code = error_code 
 
        def __unicode__(self): 
            return repr(self.error_desc) 
 
 
    # .... some methods ........ 
 
 
    ERROR_CODES_MAPPING_DICT = { 
        # Line where exception is raised: 
        JsonCleaner.NormalizeError.ERROR_NO_CODE:       WrongJsonError.NO_ERROR,  
        JsonCleaner.NormalizeError.ERROR_LACK_OF_FIELD: WrongJsonError.ERROR_LACK_OF_FIELD, 
        JsonCleaner.NormalizeError.ERROR_TYPE_MISMATCH: WrongJsonError.ERROR_TYPE_MISMATCH, 
        JsonCleaner.NormalizeError.ERROR_WRONG_VALUE:   WrongJsonError.ERROR_WRONG_VALUE,  
    } 

我做错了什么?

请您参考如下方法:

类名不能在类作用域内使用,因为在类被完全定义之前名称实际上并没有被绑定(bind)。将字典文字移到类范围之外。

JsonCleaner.ERROR_CODES_MAPPING_DICT = ...