質問

I'm having trouble with global variables, yet again. I'll put my code into a small example. I assign a variable named var1, in function1. Now I want to call that variable in function 2 and then print the results of function 2

If I use this code, I get a var1 is not defined.

def function1():
    global var1
    var1 = 'Hello'

def function2():
    return var1


print function2()

How do i fix this?

役に立ちましたか?

解決

You need to actually call function1() first.

The global keyword only tells Python that when you call the function, any assignment to var1 should be to a global, not a local name. But that doesn't magically make var1 appear until you actually execute that assignment. Until you call function1, there is no global var1.

Python has no declarations; names are either bound or not bound.

Demo:

>>> def function1():
...     global var1
...     var1 = 'Hello'
... 
>>> def function2():
...     return var1
... 
>>> function2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in function2
NameError: global name 'var1' is not defined
>>> function1()
>>> function2()
'Hello'

他のヒント

If you want to make global var1 in function2(), you should call function1in function2. Doing that var1 became visible and accessible to return in function2:

 >>>def function2():
 ...    function1()
 ...    return var1
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top