在封闭范围内的赋值错误之前避免引用的 Pythonic 方法是什么? [英] What is the Pythonic way to avoid reference before assignment errors in enclosing scopes?

查看:45
本文介绍了在封闭范围内的赋值错误之前避免引用的 Pythonic 方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我说的是一般情况.举个例子:

I'm speaking about the general case. Here's an example:

c = 1
def a():
    def b():
        print(c)
    b()
    c = 2

a()

此代码将返回以下错误:NameError:在封闭范围内赋值之前引用了自由变量c".虽然逻辑假设是输出应该是 1.这个问题的 Pythonic 解决方案是什么?使用 globalnonlocal 语句(我不喜欢)?也许只是避免这种情况,即多个作用域共享具有相同名称的变量?

This code will return the following error: NameError: free variable 'c' referenced before assignment in enclosing scope. While the logical assumption is that the output should be 1. What is the Pythonic solution to this issue? Use the global or nonlocal statements (which I don't like)? Maybe just avoid such situations, where multiple scopes share variables with identical names?

推荐答案


将其作为参数传递

当将外部变量作为参数传递时,避免重用名称,除非该变量不可能将任何其他变量作为参数处理,否则这并不重要,否则如果传递 d 下一次,您在函数内对 c 进行操作.

When passing a outside variable as a parameter, avoid reusing names unless it's not possible that this variable can handle any other variable as parameter, then it doesn't really matter otherwise it will be confusing if you pass d the next time and you do operations on c within the function.

其次,的值 c 即使从param更改名称,也不会在函数内修改c (它没有什么意义)作为变量传递时,因为它不被视为全局变量,即使变量是一个对象,它也只会是这个函数中的一个对象,除非你传递它进入一个班级.

Secondly, the value of c will not get modified within the function even if changing name from param to c (it has very little meaning) when passing as a variable because it's not considered as a global varaible, even tho the variable is an object it will only be a object in this function unless you pass it into a class.

c = 1
def a(param):
    def b():
        print(param)
    b()
    param = 2

a(c)

如果您不想将其作为参数传递并且仍希望在函数之外影响 c,则需要坚持使用全局选项.全局选项影响外部" c 变量,如您所愿......但这并不是真正被认为是最佳实践,如果可能的话,尽量使用它.

You would need to stick to the global option if you don't want to pass it as a parameter and you still want to affect c outside of your function. The global option will affect the "outside" c variable as your want it to.. but this is not really considered best practice, avid it if possible.

c = 1
def a():
    global c
    def b():
        print(c)
    b()
    c = 2

a()

以下是我的建议:

c = 1
def a(param):
    def b():
        print(param)
    b()
    param = 2
    return param

c = a(c)

甚至:

c = 1
def b(param):
    print(param)
def a(param):
    b(param)
    param = 2
    return param

c = a(c)

这篇关于在封闭范围内的赋值错误之前避免引用的 Pythonic 方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆