什么时候使用非局部关键字?
我不明白为什么我可以在此处使用系列变量:
def calculate_mean():
series = []
def mean(new_value):
series.append(new_value)
total = sum(series)
return total/len(series)
return mean
但是我不能在此处使用计数和总变量(在分配前引用了变量):
def calculate_mean():
count = 0
total = 0
def mean(value):
count += 1
total += value
return total/count
return mean
仅当我使用这样的非局部关键字时,它才能使用:
def calculate_mean():
count = 0
total = 0
def mean(value):
nonlocal count, total
count += 1
total += value
return total/count
return mean
这是我使用carculate_mean()的方式
mean = calculate_mean()
print(mean(5))
print(mean(6))
print(mean(7))
print(mean(8))
I don't understand why I can use series variable here:
def calculate_mean():
series = []
def mean(new_value):
series.append(new_value)
total = sum(series)
return total/len(series)
return mean
But I can't use count and total variables here (variable referenced before assignment):
def calculate_mean():
count = 0
total = 0
def mean(value):
count += 1
total += value
return total/count
return mean
It works only if I use nonlocal keyword like this:
def calculate_mean():
count = 0
total = 0
def mean(value):
nonlocal count, total
count += 1
total += value
return total/count
return mean
This is how I use calculate_mean()
mean = calculate_mean()
print(mean(5))
print(mean(6))
print(mean(7))
print(mean(8))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您面对的是,在一种情况下,您可以在可变的对象中使用,然后在对象上操作(当它是列表时) - 在其他情况下,您正在使用可相似的对象进行操作并使用分配。运算符(增强Assingment
+=
)。默认情况下,Python定位所有 read 并相应使用的非本地变量 - 但是,如果在内部范围中分配了变量,则Python假定它是局部变量(即IE局部变量,函数),除非明确声明为非本地。
What you are facing there is that in one case, you have in the vareiable a mutable object, and you operate on the object (when it is a list) - and in the other case you are operating on an imutable object and using an assignment operator (augmented assingment
+=
) .By default, Python locates all non-local variables that are read and use then accordingly - but if a variable is assigned to in the inner scope, Python assumes it is a local variable (i.e. local to the inner function), unless it is explicitly declared as nonlocal.