非本地关键字的工作原理如何?

时间:2017-07-17 04:28:41

标签: python python-3.x closures python-nonlocal

在下面的代码中,

    Imports System.ComponentModel
    Imports System.Threading



  Public Class Form1


Private flag As Boolean = False
Dim Completed As Boolean = False


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    BackgroundWorker1.RunWorkerAsync()
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


    flag = True

    'Do
    '  do loop never see's a true flag
    'Loop Until Completed

    Thread.Sleep(500)

    If Completed = True Then
        Label1.BackColor = Color.Red
    End If

End Sub

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    Do
        Thread.Sleep(25)
    Loop Until flag


End Sub


Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As 
RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    Completed = True
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles 
Button2.Click
    Label1.Text = flag.ToString
End Sub
 End Class

python interpreter在def makeAverage(): series = [] def average(newValue): series.append(newValue) total = sum(series) return total/len(series) return average 中不希望seriesnonlocal

但是在下面的代码中

average()

问题:

为什么python解释器需要def makeAverage(): count = 0 total = 0 def average(newValue): nonlocal count, total count += 1 total += newValue return total/count return average & counttotal中声明了nonlocal

1 个答案:

答案 0 :(得分:3)

如果您在该函数的任何位置指定,则该变量被视为函数的本地变量,否则您不会标记该变量(使用globalnonlocal )。在您的第一个示例中,series内的average没有分配,因此它不被视为average的本地,因此使用了封闭函数的版本。在第二个示例中,total内部有countaverage的分配,因此需要将它们标记为nonlocal以从封闭函数访问它们。 (否则你会得到一个UnboundLocalError,因为average尝试在第一次分配它们之前读取它们的值。)