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

Python建造者模式中->AlgDispenser出现未解析引用错误求助

解决Python建造者模式中返回类型未解析引用的问题

针对你代码中addAlgorithm方法返回类型AlgDispenser出现未解析引用的错误,有两种常见解决方式:

方式一:使用字符串字面量标注返回类型

在Python类的定义过程中,类本身还未完成定义,直接引用类名会导致解析错误。将返回类型用字符串包裹即可解决:

class AlgDispenser:
    # super class to output an algorithm out of a selection of algorithms
    def __init__(self, *algorithms: Algorithm):
        super().__init__()
        self._algs: list[Algorithm] = []
        self._activeAlg: int = 0
        for i in range(0, len(algorithms)):
            self._algs.append(algorithms[i])
            
    def addAlgorithm(self, alg: Algorithm) -> 'AlgDispenser':
        # builder pattern
        self._algs.append(alg)
        return self

方式二:使用Self类型(Python 3.11+)

如果你的Python版本是3.11及以上,可以从typing模块导入Self类型,它专门用来指代当前类:

from typing import Self

class AlgDispenser:
    # super class to output an algorithm out of a selection of algorithms
    def __init__(self, *algorithms: Algorithm):
        super().__init__()
        self._algs: list[Algorithm] = []
        self._activeAlg: int = 0
        for i in range(0, len(algorithms)):
            self._algs.append(algorithms[i])
            
    def addAlgorithm(self, alg: Algorithm) -> Self:
        # builder pattern
        self._algs.append(alg)
        return self

另外需要注意:代码中的Algorithm类型如果是自定义类,要确保它已在当前作用域中定义或正确导入,否则也会出现类似的未解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:02:36