【问题标题】:Python mixing global and local variable? [duplicate]Python混合全局变量和局部变量? [复制]
【发布时间】:2019-06-05 21:52:03
【问题描述】:

我将一个全局变量“i”初始化为 0 和一个函数定义。 在def中,我想将本地'j'初始化为全局'i',然后将1分配给全局'i',但是编译器认为当我将1分配给'i'时,我将其初始化。

这不起作用:

i = 0
def doSomething():
    j = i # compiler throws UnboundLocalError here
    i = 1

这是有效的:

i = 0
def doSomething():
    j = i

【问题讨论】:

  • 对函数体中任意位置的变量赋值使该变量local
  • 我会解释一个标题“Python 混合全局和局部变量?”到“为什么 Python 保护免受使用全局和局部变量?”。答案是“因为你不应该”。
  • 简答,没有明确的global varvar 在本地范围内是只读的。

标签: python python-3.x variables variable-assignment


【解决方案1】:

修改前需要在函数内声明全局变量。

 i = 0
def doSomething():
    global i #needed to modify the global variable.
    j = i # compiler throws UnboundLocalError here
    i = 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-24
    • 2016-12-27
    • 2015-08-19
    • 2013-01-06
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    相关资源
    最近更新 更多