1

I have code that is like this

global _portlist1

def Identify():
 #do something
 _portlist1=["a","b"]

def RunTest():
  print _portlist1
  #do something else

def run():
 Identify()
 RunTest()

In RunTest(), _portlist1 is empty, but it was defined in Identify() . Since its a global variable, shouldn't its value have been changed after running Identify()

4

2 回答 2

5

You need this:

def Identify():
    global _portlist1
    _portlist1 = ["a", "b"]

I.e. declare the global variable inside the function. Otherwise, a local variable will shadow it.

于 2013-07-19T16:03:59.590 回答
5

_portlist1 in Identify() is local. Python doesn't care that it has the same name as another variable outside the function. You have to declare it as global inside the function as well.

_portlist1 = None

def Identify():
    global _portlist1
    _portlist1 = ["a","b"]

Although you don't need to assign something to _portlist1 outside of the function, I like to do so. Otherwise, if you don't call Identify(), you'll get a NameError. Of course, you can always catch a NameError; it's just my style to do LBYL in this circumstance, since it also makes it easier to read IMHO.

于 2013-07-19T16:04:51.767 回答