在下面的代码中,
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
中不希望series
为nonlocal
。
但是在下面的代码中
average()
问题:
为什么python解释器需要def makeAverage():
count = 0
total = 0
def average(newValue):
nonlocal count, total
count += 1
total += newValue
return total/count
return average
& count
在total
中声明了nonlocal
?
答案 0 :(得分:3)
如果您在该函数的任何位置指定,则该变量被视为函数的本地变量,否则您不会标记该变量(使用global
或nonlocal
)。在您的第一个示例中,series
内的average
没有分配,因此它不被视为average
的本地,因此使用了封闭函数的版本。在第二个示例中,total
内部有count
和average
的分配,因此需要将它们标记为nonlocal
以从封闭函数访问它们。 (否则你会得到一个UnboundLocalError,因为average
尝试在第一次分配它们之前读取它们的值。)