代码之家  ›  专栏  ›  技术社区  ›  Wizard

递归函数体中的自隐行为

  •  0
  • Wizard  · 技术社区  · 5 年前

    我碰巧在一个类方法中运行了这样一个片段,并删除了 self 在辩论中,但要把它留在身体里。

    def bi_search(a, x, lo=0, hi=None) -> int:
        if hi == None:
            hi = len(a)
    
        if lo < 0:
            raise ValueError('low must be non-negative')
    
        if lo == hi:
            return None
    
        mid = (lo + hi) // 2
    
        if x == a[mid]:
            return x
        if x > a[mid]:
            lo = mid + 1
            return self.bi_search(a, x, lo, hi)
        if x < a[mid]:
            hi = mid
            return self.bi_search(a, x, lo, hi)
    
    print(bi_search([1, 2, 3, 4], 3))
    

    它工作得很好,没有报告任何错误, 为什么不报告NameError。

    enter image description here

    如果尝试了self.bi_搜索它,则报告名称错误

    In [2]: self.bi_search                   
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-2-f458d3bc4fee> in <module>
    ----> 1 self.bi_search
    
    NameError: name 'self' is not defined
    
    0 回复  |  直到 5 年前
        1
  •  3
  •   deceze    5 年前

    它不起作用。你的代码从来没有碰到过那些条件语句 self . 如果是的话,它会产生 NameError .