更新时间:2023-09-01 21:13:40
原因是 losses
被定义为一个全局变量.在函数(局部作用域)中,您可以松散地说,从全局变量中读取但不能修改它们.
The reason is that losses
is defined as a global variable. Within functions (local scope), you can, loosely speaking, read from global variables but not modify them.
这会起作用:
losses = 0
def f():
print(losses)
f()
这不会:
losses = 0
def f():
losses += 1
f()
如果您希望变量具有局部作用域,则应该将它们分配给 函数体内的变量.如果您明确想要修改全局变量,则需要在函数体中使用例如 global loss
来声明它们.
You should assign to your variables within your function body if you want them to have local scope. If you explicitly want to modify global variables, you need to declare them with, for example, global losses
in your function body.