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

嵌套类中函数递归调用报错:name 'Algorithms'未定义

问题分析与修复方案

核心错误点

  1. 类名拼写错误:递归调用时写的Algorithms.SearchAlgorithm是错的,原代码里的类是SearchAlgorithms(多了个s),这是触发「名称未定义」错误的直接原因之一。
  2. 嵌套类内的全局引用问题:在RecursiveBinarySearch类定义内部,直接用Algorithms.SearchAlgorithms.RecursiveBinarySearch调用自身方法,此时外层类可能还未完成加载,Python无法识别这个全局名称。
  3. 方法定义不规范:类中的RecursiveBinarySearchAlgo和Verify没有声明为静态方法/类方法,直接调用会导致参数错误(Python会自动传入实例/类作为第一个参数)。
  4. 测试代码位置错误:测试代码写在类的顶层代码块中,会在类定义阶段就执行,不符合常规写法,也容易引发作用域问题。

修复后的代码

class Algorithms:
    class SearchAlgorithms:
        class RecursiveBinarySearch:
            @staticmethod
            def RecursiveBinarySearchAlgo(List, Target):
                '''
                Return true value if it exists and a false if it doesn't
                '''
                if len(List) == 0:
                    return False
                else:
                    Midpoint = len(List) // 2
                    if List[Midpoint] == Target:
                        return True
                    else:
                        # 用当前类直接调用方法,避免外层类引用问题
                        if List[Midpoint] < Target:
                            return RecursiveBinarySearch.RecursiveBinarySearchAlgo(List[Midpoint + 1:], Target)
                        else:
                            return RecursiveBinarySearch.RecursiveBinarySearchAlgo(List[:Midpoint], Target)    

            @staticmethod
            def Verify(Result):
                print("Target found: ", Result)

# 测试代码移到类外部
if __name__ == "__main__":
    Numbers = [1,2,3,4,5,6,7,8]
    # 测试用例1:查找不存在的目标
    Result = Algorithms.SearchAlgorithms.RecursiveBinarySearch.RecursiveBinarySearchAlgo(Numbers, 12)
    Algorithms.SearchAlgorithms.RecursiveBinarySearch.Verify(Result)
    # 测试用例2:查找存在的目标
    Result = Algorithms.SearchAlgorithms.RecursiveBinarySearch.RecursiveBinarySearchAlgo(Numbers, 5)
    Algorithms.SearchAlgorithms.RecursiveBinarySearch.Verify(Result)

修复说明

  • 给RecursiveBinarySearchAlgo和Verify加上@staticmethod装饰器,让它们可以直接通过类调用,不需要实例化。
  • 递归调用时改用当前类RecursiveBinarySearch来调用方法,避免依赖外层类的全局引用。
  • 修正了类名拼写错误(SearchAlgorithm→SearchAlgorithms)。
  • 将测试代码移到类外部,并放在if __name__ == "__main__"块中,确保只有在直接运行脚本时才执行测试。

运行修复后的代码,会输出预期结果:

Target found:  False
Target found:  True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:35:34