【问题标题】:Local Variable referenced before assignment even though it is assigned分配前引用的局部变量,即使已分配
【发布时间】:2020-07-22 19:21:22
【问题描述】:
class Trie:
    def __init__(self):
        self.children = [None] * 26
        self.count = 0

def solve(words,k):
    fap=0
    trie = Trie()
    for x in words:
        cur = trie
        for ch in x:
            i = ord(ch) - ord('A')
            if(cur.children[i] is None):
                cur.children[i] = Trie()
            cur = cur.children[i]
        cur.count+=1
    
    def dfs(node,depth=0):
        for c in range (0,26):
            if(node.children[c] is not None):
                dfs(node.children[c],depth+1)
                node.count+=node.children[c].count
        while(node.count>=k):
            fap+=depth
            node.count-=k
    dfs(trie)
    return fap

words 初始化为['foo','bar'] k 初始化为 2

线

fap+= depth

给出错误:

local variable 'fap' referenced before assignment

即使fapsolve 函数的第一行被赋值为0。

【问题讨论】:

  • 但是DFS函数在solve函数里面
  • @Ronald 缩进是正确的,dfs是在solve里面定义的,在solve的末尾调用。
  • 我的错误。我删除了它并能够重现错误。
  • 如果我将 fap 变量声明为数组而不是 fap 变量,则不会产生此错误.. 为什么会这样?

标签: python variables scope


【解决方案1】:

这一行

fap+=depth

dfs 函数内,而不是solve

当您在dfs 中分配给fap 时,默认情况下它将被视为dfs 的本地,因此会出现错误。

如果你想从封闭作用域更新fap变量solve函数,你必须声明它nonlocal

   def dfs(node,depth=0):
        nonlocal fap
        for c in range (0,26):
        ...
 

【讨论】:

    【解决方案2】:

    您需要在dfs() 函数中添加nonlocal fap,否则您将无法在内部函数中访问变量

    【讨论】:

    • 因为您可能不再分配给它,而是通过附加对其进行了变异,因此它不会被视为本地。一般规则是,如果您在函数体的任何位置为变量赋值,则它被视为函数的局部变量,除非您将其声明为全局或非局部的。
    • 我已经改变了第一个元素,我正在处理数组的第 0 个索引
    猜你喜欢
    • 2020-10-02
    • 2020-07-08
    • 1970-01-01
    • 2015-11-16
    • 2017-08-10
    • 2020-01-16
    • 2019-12-05
    • 2017-09-19
    • 2020-09-26
    相关资源
    最近更新 更多