类定义中的 NameError [英] NameError within class definition

查看:51
本文介绍了类定义中的 NameError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想如下定义一个类:

class ConfigManager:
    @classmethod
    def load_config(cls):
        # do some complex stuff to load something
        return config

    __CONFIG = ConfigManager.load_config()

    @classmethod
    def get_config(cls):
        return cls.__CONFIG

然后当我运行以下代码时,它报告了一个NameError:

And then when I run the following code, it reports a NameError:

x = ConfigManager.get_config()

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    class ConfigManager:
  File "test.py", line 7, in ConfigManager
    __CONFIG = ConfigManager.load_config()
NameError: name 'ConfigManager' is not defined

为什么会出现这个错误?是不是因为Python代码是通过解释执行的,到第7行时,class ConfigManager还没有完成定义?

Why does this error occur? Is it because Python code is executed by interpretation and when it goes to line 7, class ConfigManager is not yet finished to be defined?

推荐答案

类对象只存在于类主体和所有类装饰器之后.这意味着您不能在 ConfigManager 主体内部使用名称 ConfigManager.这包括您在课程完成之前调用的任何函数或方法.

A class object only exists by its name after the class body and all class decorators are evaluated. What that means is that you cannot use the name ConfigManager inside the ConfigManager body itself. This also includes any function or method you call before the class is completed.

在构建类主体时,您可以引用先前在类主体中定义的名称和先前在类主体外定义的名称.

While building the class body, you can refer to names previously defined in the class body and names previously defined outside of the class body.

external_name = 'External'

class Demo:
    internal_name = 'Internal'
    print('Body see', external_name, internal_name)
    # throws an error
    print('Body does not see', late_internal_name, late_external_name)
    late_internal_name = 'LateInternal'

late_external_name = 'LateExternal'

这意味着您可以定义一个函数来加载您的配置只要它不需要类对象.请注意,即使在类中定义,当您访问它时,这也不是 (class-) 方法.

This means you can define a function to load your configuration as long as it does not need the class object. Note that even when defined inside the class, this is not a (class-) method by the time you access it.

class ConfigManager:
    # not a method - does not receive cls/self
    def load_config():
        # do some complex stuff to load something
        return {}

    # call helper as a regular function
    __CONFIG = load_config()
    # clean up helper since it is not a proper method
    del load_config

    @classmethod
    def get_config(cls):
        return cls.__CONFIG

或者,如果需要,您可以延迟加载配置.

Alternatively, you can lazily load the config if needed.

class ConfigManager:
    _CONFIG = None

    @classmethod
    def _load_config(cls):
        # do some complex stuff to load something
        return {}

    @classmethod
    def get_config(cls):
        if cls._CONFIG is None:
            cls._CONFIG = cls._load_config()
        return cls._CONFIG

这篇关于类定义中的 NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆