4

I am learning Python. A book on Python 3 says the following code should work fine:

def funky():
    print(myvar)
    myvar = 20
    print(myvar)

myvar = 10
funky()

But when I run it in Python 3.3, I got the

UnboundLocalError: local variable 'myvar' referenced before assignment

error. My understanding is that the first print(myvar) in funky should be 10 since it's a global variable. The second print(myvar) should be 20 since a local myvar is defined to be 20. What is going on here? Please help clarify.

4

3 に答える 3

8

You need to call global in your function before assigning a value.

def funky():
    global myvar
    print(myvar)
    myvar = 20
    print(myvar)

myvar = 10
funky()

Note that you can print the value without calling global because you can access global variables without using global, but attempting to assign a value will require it.

于 2013-01-20T04:53:25.447 に答える
2

ドキュメントから:

プログラムテキスト内の名前の各出現は、使用を含む最も内側の機能ブロックで確立されたその名前のバインディングを参照します。

globalこれは、それまたはnonlocal(ネストされた関数)を宣言しない限りmyvar、ローカル変数または自由変数(myvar関数で定義されていない場合)であることを意味します。

その本は正しくない。同じブロック内で、名前は同じ変数を表します(このmyvar例では、ローカル変数。同じ名前のグローバル変数がある場合でも、定義するまで使用できません)。また、関数の外部で値を変更することもできます。つまり、 65ページの最後のテキストも正しくありません。次の作品:

def funky(): # local
    myvar = 20 
    print(myvar) # -> 20
myvar = 10 # global and/or local (outside funky())
funky()
print(myvar) # -> 10 (note: the same)

 

def funky(): # global
    global myvar
    print(myvar) # -> 10
    myvar = 20
myvar = 10
funky() 
print(myvar) # -> 20 (note: changed)

 

def funky(): # free (global if funky is not nested inside an outer function)
    print(myvar) # -> 10
myvar = 10
funky() 

 

def outer():
    def funky():  # nonlocal
        nonlocal myvar
        print(myvar) # -> 5
        myvar = 20
    myvar = 5 # local
    funky()
    print(myvar) # -> 20 (note: changed)
outer()
于 2013-01-20T06:01:14.740 に答える
0

Python "assumes" that we want a local variable due to the assignment to myvar inside of funky(), so the first print statement throws ## UnboundLocalError: local variable 'myvar' referenced before assignment ## error message. Any variable which is changed or created inside of a function is local, if it hasn't been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword "global", as can be seen in the following example:

def f():
  global s
  print s
  s = "That's clear."
  print s 


s = "Python is great!" 
f()
print s
于 2014-09-24T08:14:07.533 に答える