You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何处理类变量为自身子类的引用问题?

解决Python父类类变量引用未定义子类的问题

你遇到的问题本质是Python类定义的执行顺序限制:定义State类时,StartState和EndState还未被创建,直接赋值会触发NameError;但先定义子类又会因父类State未定义导致继承报错。下面提供几种可行的解决思路:

方法1:子类定义后再赋值父类类变量

先定义父类,再定义子类,最后手动给父类的类变量赋值,完全贴合Python执行逻辑:

class State:
    START: "State"  # 用字符串类型注解暂存类型提示
    END: "State"

    @classmethod
    def get_current(cls, context: Context) -> "State":
        if context.just_beginning:
            return cls.START
        return cls.END

class StartState(State):
    ...

class EndState(State):
    ...

# 子类定义完成后补全赋值
State.START = StartState()
State.END = EndState()

方法2:类属性延迟加载(@classmethod + property)

把START和END改成类属性形式,第一次访问时才初始化子类实例,适合懒加载场景:

class State:
    _START: "State" = None
    _END: "State" = None

    @classmethod
    @property
    def START(cls) -> "State":
        if cls._START is None:
            cls._START = StartState()
        return cls._START

    @classmethod
    @property
    def END(cls) -> "State":
        if cls._END is None:
            cls._END = EndState()
        return cls._END

    @classmethod
    def get_current(cls, context: Context) -> "State":
        if context.just_beginning:
            return cls.START
        return cls.END

class StartState(State):
    ...

class EndState(State):
    ...

方法3:利用__init_subclass__自动注册子类

通过Python的__init_subclass__钩子,让子类定义时自动注册到父类的类变量中,适合多子类动态注册场景:

class State:
    START: "State"
    END: "State"

    @classmethod
    def get_current(cls, context: Context) -> "State":
        if context.just_beginning:
            return cls.START
        return cls.END

    @classmethod
    def __init_subclass__(cls, state_type=None, **kwargs):
        super().__init_subclass__(**kwargs)
        if state_type == "start":
            State.START = cls()
        elif state_type == "end":
            State.END = cls()

# 定义子类时指定类型标识完成自动注册
class StartState(State, state_type="start"):
    ...

class EndState(State, state_type="end"):
    ...

内容的提问来源于stack exchange,提问作者Chetchaiyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 15:52:22