什么时候使用非局部关键字?

发布于 2025-01-22 09:55:44 字数 829 浏览 1 评论 0原文

我不明白为什么我可以在此处使用系列变量:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

残花月 2025-01-29 09:55:44

您面对的是,在一种情况下,您可以在可变的对象中使用,然后在对象上操作(当它是列表时) - 在其他情况下,您正在使用可相似的对象进行操作并使用分配。运算符(增强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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文